mirror of https://github.com/vitalif/phantomjs
Added "includeJs()" to "page".
* It includes a script in the page * It uses a callback to ensure any code dependent on the include runs afterwards * It uses the signal "javaScriptAlertSent" to do the trick (is there another way to be notified of the "onLoad" event from outside the page context?) * It uses a "private" slot "_appendScriptElement" to pass the script url in the page context (is there a better way?)1.2
parent
11c8322718
commit
75403737c4
|
@ -0,0 +1,19 @@
|
|||
// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"
|
||||
|
||||
var page = new WebPage();
|
||||
|
||||
page.onConsoleMessage = function(msg) {
|
||||
console.log(msg);
|
||||
};
|
||||
|
||||
page.open("http://www.phantomjs.org", function(status) {
|
||||
if ( status === "success" ) {
|
||||
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
|
||||
page.evaluate(function() {
|
||||
console.log("$(\"#intro\").text() -> " + $("#intro").text());
|
||||
});
|
||||
phantom.exit();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -83,5 +83,22 @@ window.WebPage = function() {
|
|||
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 {
|
||||
this.javaScriptAlertSent.disconnect(this);
|
||||
} catch (e) {}
|
||||
}
|
||||
});
|
||||
|
||||
// Append the script tag to the body
|
||||
this._appendScriptElement(scriptUrl);
|
||||
};
|
||||
|
||||
return page;
|
||||
}
|
||||
|
|
|
@ -42,4 +42,9 @@
|
|||
"el.dispatchEvent(ev);" \
|
||||
"})(this);"
|
||||
|
||||
#define JS_APPEND_SCRIPT_ELEMENT "var el = document.createElement('script');" \
|
||||
"el.onload = function() { alert('%1'); };" \
|
||||
"el.src = '%1';" \
|
||||
"document.body.appendChild(el);"
|
||||
|
||||
#endif // CONSTS_H
|
||||
|
|
|
@ -514,3 +514,7 @@ bool WebPage::injectJs(const QString &jsFilePath) {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void WebPage::_appendScriptElement(const QString &scriptUrl) {
|
||||
m_mainFrame->evaluateJavaScript( QString(JS_APPEND_SCRIPT_ELEMENT).arg(scriptUrl) );
|
||||
}
|
||||
|
|
|
@ -73,6 +73,7 @@ public slots:
|
|||
QVariant evaluate(const QString &code);
|
||||
bool render(const QString &fileName);
|
||||
bool injectJs(const QString &jsFilePath);
|
||||
void _appendScriptElement(const QString &scriptUrl);
|
||||
|
||||
// moc does not understand QT_VERSION_CHECK and hence the encoded hex
|
||||
#if QT_VERSION >= 0x040600
|
||||
|
|
Loading…
Reference in New Issue