问题
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