【发布时间】:2016-07-20 21:15:34
【问题描述】:
我有一个Casper JS 脚本(Casper JS 基于Phantom JS),它将另一个脚本注入到外部 URL 中。注入的脚本在加载 DOM 后运行代码,类似于 jQuery 的 $(document).ready() 的工作方式。
如果注入的脚本包含 JavaScript 错误,那么如果在 DOM 之后加载,Casper JS 将不会捕获它。如果立即运行,Casper 将捕获错误。
下面的代码不会输出错误ReferenceError: Strict mode forbids implicit creation of global property 'string'。如果您查看最底线,则可以交换行中的 cmets 以获取此错误。我希望即使在加载 DOM 后运行代码时也会发生此错误。
要运行代码,安装 Casper JS 并在控制台中输入:casperjs casper.js
casper.js
// Include Casper's "utils" so we can dump variables.
var require = patchRequire(require);
var utils = require('utils');
// Open a URL and inject our JS.
var casper = require('casper').create();
casper.start('http://example.com/', function() {
casper.page.injectJs('inject.js');
});
// Wait a moment to give everything time to load, then check that the function
// exists and returns something.
casper.wait(1000, function() {
var testValue = casper.evaluate(function() {
return test();
});
casper.echo(testValue);
});
// If there are any errors along the way, then print them.
casper.on('page.error', function(msg, trace) {
casper.echo(msg);
casper.echo(utils.dump(trace));
});
// Actually run everything.
casper.run();
inject.js
// Be strict on this page so that errors occur.
'use strict';
function run() {
window.test = function() {
// An error will occur here because the variable was never declared.
testing = 'test';
return testing;
}
}
// If the below line is used, then "ReferenceError: Strict mode forbids implicit
// creation of global property 'string'" appears as expected.
// run();
// If the below line is used instead of the one above, then the same error does
// not appear.
document.addEventListener('DOMContentLoaded', run);
【问题讨论】:
-
casper.on('page.error') 应该在页面上显示任何错误,它不起作用吗?
-
不,正如我所说,如果 run() 函数是通过 DOMContentLoaded 事件侦听器运行而不是裸运行,它不会显示 ReferenceError。
标签: javascript dom phantomjs casperjs code-injection