Files
phantomjs/python/pyphantomjs/bootstrap.js
T

77 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

2011-05-31 16:23:06 -07:00
// This allows creating a new web page using the construct "new WebPage",
// which feels more natural than "phantom.createWebPage()".
window.WebPage = function() {
var page = phantom.createWebPage(),
handlers = {};
2011-05-31 16:23:06 -07:00
function defineSetter(handlerName, signalName) {
page.__defineSetter__(handlerName, function(f) {
if (handlers && typeof handlers[signalName] === 'function') {
try {
this[signalName].disconnect(handlers[signalName]);
} catch (e) {}
}
handlers[signalName] = f;
this[signalName].connect(handlers[signalName]);
});
}
2011-05-31 16:23:06 -07:00
// deep copy
page.settings = JSON.parse(JSON.stringify(phantom.defaultPageSettings));
defineSetter("onLoadStarted", "loadStarted");
defineSetter("onLoadFinished", "loadFinished");
defineSetter("onResourceRequested", "resourceRequested");
defineSetter("onResourceReceived", "resourceReceived");
defineSetter("onAlert", "javaScriptAlertSent");
2011-05-31 16:23:06 -07:00
defineSetter("onConsoleMessage", "javaScriptConsoleMessageSent");
2011-05-31 16:23:06 -07:00
page.open = function () {
if (arguments.length === 1) {
this.openUrl(arguments[0], 'get', this.settings);
return;
}
2011-05-31 16:23:06 -07:00
if (arguments.length === 2) {
this.onLoadFinished = arguments[1];
2011-05-31 16:23:06 -07:00
this.openUrl(arguments[0], 'get', this.settings);
return;
} else if (arguments.length === 3) {
this.onLoadFinished = arguments[2];
2011-05-31 16:23:06 -07:00
this.openUrl(arguments[0], arguments[1], this.settings);
return;
} else if (arguments.length === 4) {
this.onLoadFinished = arguments[3];
2011-05-31 16:23:06 -07:00
this.openUrl(arguments[0], {
operation: arguments[1],
data: arguments[2]
}, this.settings);
return;
}
throw "Wrong use of WebPage#open";
};
page.includeJs = function(scriptUrl, onScriptLoaded) {
// Register temporary signal handler for 'alert()'
this.javaScriptAlertSent.connect(function(msgFromAlert) {
if ( msgFromAlert === scriptUrl ) {
// Resource loaded, time to fire the callback
onScriptLoaded(scriptUrl);
// And disconnect the signal handler
try {
2011-06-20 18:55:05 -04:00
this.javaScriptAlertSent.disconnect(arguments.callee);
} catch (e) {}
}
});
// Append the script tag to the body
this._appendScriptElement(scriptUrl);
};
2011-05-31 16:23:06 -07:00
return page;
}