3

I would like to add a JavaScript <script></script> tag, containing or sourcing untrusted code, to web pages PhantomJS visits, and have the page behave as if the page originally included the tag.

includeJs()/injectJs() do not do what I need - they inject code into my PhantomJS environment, but I need my code injected into the web page. Further, these functions expose my PhantomJS local variables to the untrusted code, which I do not want.

evaluate() does not do what I need either, as it will not take a string containing untrusted JavaScript. Instead, it expects my PhantomJS script to include a function I wrote.

How can I inject untrusted JavaScript into a web page I visit with PhantomJS?

1 Answer 1

3

It turns out page.evaluate() accepts arguments that are passed to your JavaScript function. Capitalizing on that, I was able to pass the actual JavaScript I want to run on my page into a function run from page.evaluate() which injects a script block into the page:

page = ...

function inject_js(js_code) {                                                                                                                                                               
    page.evaluate(function(js_code) {                                                                                                                                                       
        var js_block = document.createElement('script');                                                                                                                                    
        js_block.type = 'text/javascript';                                                                                                                                                  
        js_block.innerHTML = js_code;                                                                                                                                                       
        document.getElementsByTagName('body')[0].appendChild(js_block);                                                                                                                     
    }, js_code);                                                                                                                                                                            
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.