skip to Main Content

Is there any way to run JavaScript for an open browser tab remotely? For example if there is a tab open in a browser and I’d like to run a script in its developer console by piping the script to it from the shell. The idea being to develop the script from the comfort of my preferred editor and run it in the browser to test.

(Preferably, each run would be run in isolation such that multiple evaluations of const someVar = 1 wouldn’t conflict (as a const can’t be redefined).)

2

Answers


  1. Chosen as BEST ANSWER

    For Chromium based browsers, one can run JavaScript remotely in debugger mode:

    1. Run browser: chromium --remote-debugging-port=9222
    2. List open tabs: curl -s -o - http://127.0.0.1:9222/json
    3. Send script to page using Runtime.evaluate:
      page_id=9EB553A6AE7860E5036BCE836258E22F # sample id from step 2
      code='(function() { console.log("Hello, console!"); return 42; })()'
      jq -c -n 
        --arg code "$code" 
        '{id: 0, method: "Runtime.evaluate", "params":{expression: $code}}' 
           | websocat -t - "ws://127.0.0.1:9222/devtools/page/$page_id"
      

    In the last step, the important thing is to send a correctly escaped JavaScript as string in JSON object, I'm using jq and websocat to achieve that, but other tools will do as well.


  2. There are lots of ways to control computers remotely, such as through SSH, VNC, TeamViewer, NoMachine, etc. All of those, except SSH, allow graphical control, so you can click/type into a browser remotely with them.

    If instead you want to allow users to expose their computer to you, you could always write a browser plug-in, and it could make fetch requests to your server to get code. However, browser plug-ins do have some security restrictions that may limit you, depending on what exactly you want to accomplish.

    In particular, there are limits to what a plug-in can do with the dev console. I know some manipulation is possible, as there are plug-ins like the React Developer Tools which interact with the browser dev tools … but you’d have to research more to see exactly what the limits are. Likewise, there are also limits to what plug-ins can do to the filesystem, but I believe plug-ins can affect it (with user permission).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search