PhantomJS: Add Javascript include to web page (not to PhantomJS environment)

空扰寡人 提交于 2020-01-13 18:55:29

问题


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:


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);                                                                                                                                                                            
}


来源:https://stackoverflow.com/questions/21395141/phantomjs-add-javascript-include-to-web-page-not-to-phantomjs-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!