prasmussen / chrome-cli

Control Google Chrome from the command line
MIT License
2.61k stars 89 forks source link

Cannot use jQuery with ```chrome-cli execute``` command. #33

Closed blueabysm closed 4 years ago

blueabysm commented 8 years ago

I got an error in the console of Google Chrome Uncaught ReferenceError: $ is not defined when I executed the following command chrome-cli execute '$(".tableData a").click();' -t 532

But if I input this javascript fragment into console, everything works fine.

I tried to sleep for a while before executing to avoid not loading jQuery, but the problem remains.

Thanks for your awesome work!

emcniece commented 4 years ago

This is fairly old and I doubt you need this any more, but in case anyone else is interested: this execution runs scripts in a Chrome VM space that does not have access to the main Javascript runtime that the developer console runs in. You only get access to the HTML DOM.

You can get around this by loading jQuery yourself, but be warned: this is a hack and is in no manner safe as it eval's live code.

myscript.js:

(async () => {
    // load jQuery
    const jReq = await fetch('https://code.jquery.com/jquery-3.5.0.slim.min.js')
    jText = await jReq.text()
    eval(jText)

    // now ready for use:
    console.log(jQuery().jquery)
})()

... then in terminal:

JS=$(cat myscript.js)
chrome-cli execute "$JS" -t "1234"

As a warning to anyone else sideloading JS like this: I tried to get angular in to extract controller scopes and was unsuccessful - had to resort to jQuery.

blueabysm commented 4 years ago

Thank you @emcniece . It still helps :D