Skip to content
This repository was archived by the owner on May 12, 2025. It is now read-only.

dataserver/websocket_userscript

Repository files navigation

Userscript Communication with Python WebSocket

The main idea is to use a userscript to send data to a WebSocket server (written in Python) hosted on the local machine.

Example Applications

  • Scrape content from a page and send it to the WebSocket server to be stored in a .txt file
  • Compare dates found in an HTML table with data from an SQL database
  • Update elements dynamically

Userscript Manager

Recommended: ViolentMonkey

Other Managers: TamperMonkey, Greasemonkey

WebSocket Message Formats

To simplify message handling, Python uses Pydantic to define JSON formats and dispatch actions correctly.

A general wrapper model is defined in the code as follows:

class MessageModel(BaseModel):
    content: TextModel | SaveToFileModel | ButtonModel
    date: str

class SaveToFileModel(BaseModel):
    filename: str
    content: str

To activate the "save to file" function, send a message in this format:

{
    "content": {
        "filename": "mytext.txt",
        "content" : "file content"
    }, 
    "date" : "YYYY-MM-DDTHH:mm:ssZ"
}

Editing your userscript with IDE editor

You can use your favorite editor to modify your userscript.

Guide: https://violentmonkey.github.io/posts/how-to-edit-scripts-with-your-favorite-editor/

  1. Create a local HTTP server and access your websocket.user.js script via the browser:
python -m http.server 8080
  1. Open the browser at:
http://localhost:8080/websocket.user.js

alt text

  1. Use Ctrl+Enter to start or stop tracking changes to the file.

  2. Edit websocket.user.js using your preferred IDE.

Resources

Python: websockets

https://websockets.readthedocs.io/en/stable/

Javascript: websockets API

https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

License

CC0

This project is in the worldwide public domain.

This project is in the public domain and copyright and related rights in the work worldwide are waived through the CC0 1.0 Universal public domain dedication.

All contributions to this project will be released under the CC0 dedication. By submitting a pull request, you are agreeing to comply with this waiver of copyright interest.

About

Example of userscript communication with local websocket server

Topics

Resources

Stars

Watchers

Forks