webui-dev / webui

Use any web browser or WebView as GUI, with your preferred language in the backend and modern web technologies in the frontend, all in a lightweight portable library.
https://webui.me
MIT License
2.37k stars 146 forks source link

add extension support #307

Open osljw opened 5 months ago

osljw commented 5 months ago

Why use extension

MyWindow.show('https://www.google.com')

when url is showed, if <script src="webui.js"></script> is not exists, we will lose the connect. Using extension, we can inject webui.js, then build connect to page without webui.js

need to confirm

-        "%s\n document.addEventListener(\"DOMContentLoaded\",function(){ globalThis.webui = "
-        "new WebuiBridge({ secure: %s, token: %" PRIu32 ", port: %zu, winNum: %zu, bindList: %s, log: %s, ",
+        "%s\n addEventListener(\"load\",function(){ globalThis.webui = "
+        "new WebuiBridge({ secure: %s, token: %" PRIu32 ", host: %s, port: %zu, winNum: %zu, bindList: %s, log: %s, ",

can we use load event instead of DOMContentLoaded event ?

future

Using custom extension, if it's possible to build websocket in background.js ? we are able to establish a persistent connection with the browser, without re-establishing the websocket connection when the user refreshes the web page

hassandraga commented 5 months ago

Interesting. We need to dig into this path to see if we can improve webui.js. However, let me check and test this PR before merging.

Thank you @osljw for this.

osljw commented 5 months ago

extension\manifest.json

{
 "manifest_version": 3,
 "name": "Webui.js Injector",
 "version": "1.0",
 "permissions": ["webNavigation", "activeTab", "scripting"],
 "host_permissions": ["<all_urls>"],
 "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"],
      "run_at": "document_end"
    }
  ]
}

extension\content_script.js

console.log("========content script======");

const existingScripts = Array.from(document.querySelectorAll('script')).filter(script => script.src.endsWith('webui.js'));
if (existingScripts.length === 0) {
    const scriptElement = document.createElement('script');
    scriptElement.src = 'http://localhost:10100/webui.js';

    (document.head || document.documentElement).appendChild(scriptElement);
    console.log("Script 'webui.js' injected");
} else {
    console.log("Script 'webui.js' already exists in the document.");
}

python

MyWindow = webui.window()

extension_path = os.path.join(current_directory, 'extension')
MyWindow.set_extensions([extension_path])
MyWindow.set_port(10100) # extension inject webui.js through this port

MyWindow.show('https://www.google.com')

webui.wait()

@hassandraga I use python to dev. There is no c demo yet, the above code may be helpful.

SpikeHD commented 5 months ago

Could this also be applicable to Firefox by moving/copying the extension files to ${webui firefox userprofile}/extensions?