У меня есть сценарий Casper JS (Casper JS основан на Phantom JS), который вводит другой скрипт во внешний URL. Введенный скрипт запускает код после загрузки DOM, подобно тому, как работает jQuery $(document).ready()
.В Casper JS (на основе Phantom JS), как уловить ошибки JavaScript, которые загружаются после выполнения DOM?
Если введенный сценарий содержит ошибку JavaScript, то Каспер JS не сможет его поймать, если он загружен после DOM. Каспер поймает ошибки, если они будут запущены немедленно.
Код не вывести ошибку ReferenceError: Strict mode forbids implicit creation of global property 'string'
. Если вы посмотрите на самые нижние строки, вы можете поменять комментарии на строках, чтобы получить эту ошибку. Я хочу, чтобы эта ошибка возникала даже при запуске кода после загрузки 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') должен показывать какие-либо ошибки на странице, не работает ли он? – Vaviloff
Нет, как я уже сказал, он не будет показывать ReferenceError, если функция run() запускается через прослушиватель событий DOMContentLoaded, а не запускается голой. – Gary