0

I'm trying to execute some javascript code through CDTP and PyChromeDevTools library. The following code works:

from terminal:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

import PyChromeDevTools
chrome.Network.enable()
chrome.Page.enable()

script="t='hi,';c='this code works on the same line';console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

I have some trouble when I need to inject complex js code not on the same line, for example function with javascript requests ecc..

script="t='hi,';
c='this code works not on the same line don't work ';
console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

is it possible equal javascript file to runtime evaluate ? like this:

chrome.Runtime.evaluate(expression=file.js)

documentation of CDTP

https://chromedevtools.github.io/devtools-protocol/

  • https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string – Juraj Jan 16 '22 at 13:41

1 Answers1

1

You should just load a js code from a file into str variable

def load_text(filename, mode='r', encoding='utf-8'):
    with open(filename, mode, encoding=encoding) as f:
        txt = f.read()
return txt

file_js = load_text('file.js')
chrome.Runtime.evaluate(expression=file_js)