【发布时间】:2016-05-26 04:05:50
【问题描述】:
我正在尝试使用覆盖方法从网站收集alert。我在 google 上搜索并找到了wappalyzer,这是一个用于检测网站上的软件的 Chrome/Firefox 扩展程序。它在页面加载和收集信息时注入脚本inject.js。我的方法类似。我制作了一个本地网站并对其进行了测试。当我手动注入overwrite_alert.js 时,它就可以工作了。
但我想动态执行并应用于其他网站。所以我使用像 PhantomJS 这样的无头浏览器。以下代码我在 PhantomJS 中尝试过,但它不起作用。
我正在尝试在 phantom JS 上注入 JavaScript。喜欢这段代码:
<!DOCTYPE html>
<html>
<head>
<title>Test alert</title>
<!-- !!! Inject here !!! <script src="overwrite_alert.js"></script> -->
<script type="text/javascript" src="other_script.js"> </script>
<script type="text/javascript">
alert("Alert content");
</script>
</head>
<body>
<h1>website content</h1>
</body>
</html>
overwrite_alert.js 来自this question 的文件:
(function() {
var _alert = window.alert; // <-- Reference
window.alert = function(str) {
// do something additional
if(console) console.log(str);
//return _alert.apply(this, arguments); // <-- The universal method
_alert(str); // Suits for this case
};
})();
我尝试使用 onLoadStarted 事件和 My PhantomJS 代码:
var webPage = require('webpage');
var page = webPage.create();
var url = "https://localhost:5000/alert.html";
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE> ' + msg);
};
page.onLoadStarted = function() {
if (page.injectJs('do.js')) {
var title = page.evaluate(function() {
// returnTitle is a function loaded from our do.js file - see below
console.log("evaluate completed");
});
console.log(title);
}
}
page.open(url, function(status) {
if (status === "success") {
if (page.injectJs('do.js')) {
var title = page.evaluate(function() {
// returnTitle is a function loaded from our do.js file - see below
console.log("evaluate completed");
});
console.log(title);
phantom.exit();
}
page.render("onOpen.png");
}
});
结果:
$ phantomjs test_inject.js
CONSOLE> from onLoadStarted completed
null
CONSOLE> from page.open
null
【问题讨论】:
标签: javascript web phantomjs