Can you make a node server code communicate with HTML of a website open in browser?

Viewed 50

For example I've written a code to access a global variable of a web page and access values from it and then I want to put that value in some HTML div of that page. Now I can copy and paste this code into browser console and it will work.

But instead of pasting it in console, is there any way I can run my own server (localhost) using NodeJS and do the same from there? I mean communicate to the browser and that page which is open?

If yes, what things will I need?

1 Answers

I would use selenium-webdriver

It takes a bit of setup, but afterwards it's pretty easy

go here and click on the folder just above the one that says 'icons' (this should be the latest version of chrome webdriver)

Then, once you download the latest version, drag the exe C:\WINDOWS (if you're not on windows just move it to any folder on the PATH environment variable

now that you've done that, set up a simple script like this:

const webdriver = require('selenium-webdriver')

let driver = new webdriver.Builder().forBrowser('chrome').build();

(async function example() {
  await driver.get('http://example.com/')
  await driver.executeScript('/* your code, for example: */ document.getElementsByTagName(\'h1\')[0].innerHTML = \'test\'; console.log(\'test\')')
}())

make sure to escape (but a backslash before) any single quotes in your driver.executeScript

I would recommend learning a bit about selenium-webdrivers api so that you can to more complicated things (such as running this without actually opening a new window). I would also that you use selenium-webdriver's api (which allows you to edit webpages, click things, input keys, etc.) instead of just putting everything in an executeScript as much as you can.

Related