phontomjs webPage模块的callback

2024-05-07 02:08

本文主要是介绍phontomjs webPage模块的callback,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

Callback Triggers

These functions call callbacks, used for tests…

  • closing(page)
  • initialized()
  • javaScriptAlertSent(message)
  • javaScriptConsoleMessageSent(message)
  • loadFinished(status)
  • loadStarted()
  • navigationRequested(url, navigationType, navigationLocked, isMainFrame)
  • rawPageCreated(page)
  • resourceError(resource)
  • resourceReceived(request)
  • resourceRequested(resource)
  • urlChanged(url)

onAlert

Introduced: PhantomJS 1.0

This callback is invoked when there is a JavaScript alert on the web page. The only argument passed to the callback is the string for the message. There is no return value expected from the callback handler.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onAlert = function(msg) {console.log('ALERT: ' + msg);
};

onCallback

Stability: EXPERIMENTAL

Introduced: PhantomJS 1.6 This callback is invoked when there is a JavaScript window.callPhantom call made on the web page. The only argument passed to the callback is a data object.

Notewindow.callPhantom is still an experimental API. In the near future, it will be likely replaced with a message-based solution which will still provide the same functionality.

Although there are many possible use cases for this inversion of control, the primary one so far is to prevent the need for a PhantomJS script to be continually polling for some variable on the web page.

Examples

Send data from client to server

WebPage (client-side)

if (typeof window.callPhantom === 'function') {window.callPhantom({ hello: 'world' });
}

PhantomJS (server-side)

var webPage = require('webpage');
var page = webPage.create();page.onCallback = function(data) {console.log('CALLBACK: ' + JSON.stringify(data));// Prints 'CALLBACK: { "hello": "world" }'
};

Send data from client to server then back again

WebPage (client-side)

if (typeof window.callPhantom === 'function') {var status = window.callPhantom({secret: 'ghostly'});alert(status);// Prints either 'Accepted.' or 'DENIED!'
}

PhantomJS (server-side)

var webPage = require('webpage');
var page = webPage.create();page.onCallback = function(data) {if (data && data.secret && (data.secret === 'ghostly')) {return 'Accepted.';}return 'DENIED!';
};

Allow web page Javascript to close PhantomJS

This can be helpful when the web page running in PhantomJS needs to exit PhantomJS.

WebPage (client-side)

if (typeof window.callPhantom === 'function') {var status = window.callPhantom({command: 'exit',reason:  'User Request.'});
}

PhantomJS (server-side)

var webPage = require('webpage');
var page = webPage.create();page.onCallback = function(data) {if (data && data.command && (data.command === 'exit')) {if (data.reason) console.log('web page requested exit: '+data.reason);phantom.exit(0);}
};

onClosing

Introduced: PhantomJS 1.7

This callback is invoked when the WebPage object is being closed, either via page.closein the PhantomJS outer space or via window.close in the page’s client-side.

It is not invoked when child/descendant pages are being closed unless you also hook them up individually. It takes one argument, closingPage, which is a reference to the page that is closing. Once the onClosing handler has finished executing (returned), the WebPageobject closingPage will become invalid.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onClosing = function(closingPage) {console.log('The page is closing! URL: ' + closingPage.url);
};

onConfirm

Introduced: PhantomJS 1.6

This callback is invoked when there is a JavaScript confirm on the web page. The only argument passed to the callback is the string for the message. The return value of the callback handler can be either true or false, which are equivalent to pressing the “OK” or “Cancel” buttons presented in a JavaScript confirm, respectively.

var webPage = require('webpage');
var page = webPage.create();page.onConfirm = function(msg) {console.log('CONFIRM: ' + msg);return true; // `true` === pressing the "OK" button, `false` === pressing the "Cancel" button
};

onConsoleMessage

Introduced: PhantomJS 1.2

This callback is invoked when there is a JavaScript console message on the web page. The callback may accept up to three arguments: the string for the message, the line number, and the source identifier.

By default, console messages from the web page are not displayed. Using this callback is a typical way to redirect it.

Note: line number and source identifier are not used yet, at least in phantomJS <= 1.8.1. You receive undefined values.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onConsoleMessage = function(msg, lineNum, sourceId) {console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

onError

Introduced: PhantomJS 1.5

This callback is invoked when there is a JavaScript execution error. It is a good way to catch problems when evaluating a script in the web page context. The arguments passed to the callback are the error message and the stack trace [as an Array].

Examples

var webPage = require('webpage');
var page = webPage.create();page.onError = function(msg, trace) {var msgStack = ['ERROR: ' + msg];if (trace && trace.length) {msgStack.push('TRACE:');trace.forEach(function(t) {msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));});}console.error(msgStack.join('\n'));};

onFilePicker

Examples

var webPage = require('webpage');
var page = webPage.create();
var system = require('system');page.onFilePicker = function(oldFile) {if (system.os.name === 'windows') {return 'C:\\Windows\\System32\\drivers\\etc\\hosts';}return '/etc/hosts';
};

onInitialized

Introduced: PhantomJS 1.3

This callback is invoked after the web page is created but before a URL is loaded. The callback may be used to change global objects.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onInitialized = function() {page.evaluate(function() {document.addEventListener('DOMContentLoaded', function() {console.log('DOM content has loaded.');}, false);});
};

onLoadFinished

Introduced: PhantomJS 1.2

This callback is invoked when the page finishes the loading. It may accept a single argument indicating the page’s status'success' if no network errors occurred, otherwise 'fail'.

Also see page.open for an alternate hook for the onLoadFinished callback.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onLoadFinished = function(status) {console.log('Status: ' + status);// Do other things here...
};

onLoadStarted

Introduced: PhantomJS 1.2

This callback is invoked when the page starts the loading. There is no argument passed to the callback.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onLoadStarted = function() {var currentUrl = page.evaluate(function() {return window.location.href;});console.log('Current page ' + currentUrl + ' will be gone...');console.log('Now loading a new page...');
};

onNavigationRequested

Introduced: PhantomJS 1.6

By implementing this callback, you will be notified when a navigation event happens and know if it will be blocked (by page.navigationLocked).

Arguments

  • url : The target URL of this navigation event
  • type : Possible values include: 'Undefined''LinkClicked''FormSubmitted''BackOrForward''Reload''FormResubmitted''Other'
  • willNavigate : true if navigation will happen, false if it is locked (by page.navigationLocked)
  • main : true if this event comes from the main frame, false if it comes from an iframe of some other sub-frame.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onNavigationRequested = function(url, type, willNavigate, main) {console.log('Trying to navigate to: ' + url);console.log('Caused by: ' + type);console.log('Will actually navigate: ' + willNavigate);console.log('Sent from the page\'s main frame: ' + main);
}

onPageCreated

Introduced: PhantomJS 1.7

This callback is invoked when a new child window (but not deeper descendant windows) is created by the page, e.g. using window.open.

In the PhantomJS outer space, this WebPage object will not yet have called its own page.openmethod yet and thus does not yet know its requested URL (page.url).

Therefore, the most common purpose for utilizing a page.onPageCreated callback is to decorate the page (e.g. hook up callbacks, etc.).

Examples

var webPage = require('webpage');
var page = webPage.create();page.onPageCreated = function(newPage) {console.log('A new child page was created! Its requested URL is not yet available, though.');// DecoratenewPage.onClosing = function(closingPage) {console.log('A child page is closing: ' + closingPage.url);};
};

onPrompt

Introduced: PhantomJS 1.6

This callback is invoked when there is a JavaScript prompt on the web page. The arguments passed to the callback are the string for the message (msg) and the default value (defaultVal) for the prompt answer. The return value of the callback handler should be a string.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onPrompt = function(msg, defaultVal) {if (msg === "What's your name?") {return 'PhantomJS';}return defaultVal;
};

onResourceError

Introduced: PhantomJS 1.9

This callback is invoked when a web page was unable to load resource. The only argument to the callback is the resourceError metadata object.

The resourceError metadata object contains these properties:

  • id : the number of the request
  • url : the resource url
  • errorCode : the error code
  • errorString : the error description

Examples

var webPage = require('webpage');
var page = webPage.create();page.onResourceError = function(resourceError) {console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

onResourceReceived

Introduced: PhantomJS 1.2

This callback is invoked when a resource requested by the page is received. The only argument to the callback is the response metadata object.

If the resource is large and sent by the server in multiple chunks, onResourceReceived will be invoked for every chunk received by PhantomJS.

The response metadata object contains these properties:

  • id : the number of the requested resource
  • url : the URL of the requested resource
  • time : Date object containing the date of the response
  • headers : list of http headers
  • bodySize : size of the received content decompressed (entire content or chunk content)
  • contentType : the content type if specified
  • redirectURL : if there is a redirection, the redirected URL
  • stage : “start”, “end” (FIXME: other value for intermediate chunk?)
  • status : http status code. ex: 200
  • statusText : http status text. ex: OK

Examples

var webPage = require('webpage');
var page = webPage.create();page.onResourceReceived = function(response) {console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};

onResourceRequested

Introduced: PhantomJS 1.2

This callback is invoked when the page requests a resource. The first argument to the callback is the requestData metadata object. The second argument is the networkRequest object itself.

The requestData metadata object contains these properties:

  • id : the number of the requested resource
  • method : http method
  • url : the URL of the requested resource
  • time : Date object containing the date of the request
  • headers : list of http headers

The networkRequest object contains these functions:

  • abort() : aborts the current network request. Aborting the current network request will invoke onResourceError callback.
  • changeUrl(newUrl) : changes the current URL of the network request. By calling networkRequest.changeUrl(newUrl), we can change the request url to the new url. This is an excellent and only way to provide alternative implementation of a remote resource. (see Example-2)
  • setHeader(key, value)

Examples

Example-1

var webPage = require('webpage');
var page = webPage.create();page.onResourceRequested = function(requestData, networkRequest) {console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};

Example-2

Provide an alternative implementation of a remote javascript.

var webPage = require('webpage');
var page = webPage.create();page.onResourceRequested = function(requestData, networkRequest) {var match = requestData.url.match(/wordfamily.js/g);if (match != null) {console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));// newWordFamily.js is an alternative implementation of wordFamily.js// and is available in local pathnetworkRequest.changeUrl('newWordFamily.js'); }
};

onResourceTimeout

Introduced: PhantomJS 1.2

This callback is invoked when a resource requested by the page timeout according to settings.resourceTimeout. The only argument to the callback is the request metadata object.

The request metadata object contains these properties:

  • id: the number of the requested resource
  • method: http method
  • url: the URL of the requested resource
  • time: Date object containing the date of the request
  • headers: list of http headers
  • errorCode: the error code of the error
  • errorString: text message of the error

Examples

var webPage = require('webpage');
var page = webPage.create();page.onResourceTimeout = function(request) {console.log('Response (#' + request.id + '): ' + JSON.stringify(request));
};

onUrlChanged

Introduced: PhantomJS 1.6

This callback is invoked when the URL changes, e.g. as it navigates away from the current URL. The only argument to the callback is the new targetUrl string.

To retrieve the old URL, use the onLoadStarted callback.

Examples

var webPage = require('webpage');
var page = webPage.create();page.onUrlChanged = function(targetUrl) {console.log('New URL: ' + targetUrl);
};

这篇关于phontomjs webPage模块的callback的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/966033

相关文章

Python sys模块的使用及说明

《Pythonsys模块的使用及说明》Pythonsys模块是核心工具,用于解释器交互与运行时控制,涵盖命令行参数处理、路径修改、强制退出、I/O重定向、系统信息获取等功能,适用于脚本开发与调试,需... 目录python sys 模块详解常用功能与代码示例获取命令行参数修改模块搜索路径强制退出程序标准输入

Python pickle模块的使用指南

《Pythonpickle模块的使用指南》Pythonpickle模块用于对象序列化与反序列化,支持dump/load方法及自定义类,需注意安全风险,建议在受控环境中使用,适用于模型持久化、缓存及跨... 目录python pickle 模块详解基本序列化与反序列化直接序列化为字节流自定义对象的序列化安全注

python pymodbus模块的具体使用

《pythonpymodbus模块的具体使用》pymodbus是一个Python实现的Modbus协议库,支持TCP和RTU通信模式,支持读写线圈、离散输入、保持寄存器等数据类型,具有一定的参考价值... 目录一、详解1、 基础概念2、核心功能3、安装与设置4、使用示例5、 高级特性6、注意事项二、代码示例

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Nginx添加内置模块过程

《Nginx添加内置模块过程》文章指导如何检查并添加Nginx的with-http_gzip_static模块:确认该模块未默认安装后,需下载同版本源码重新编译,备份替换原有二进制文件,最后重启服务验... 目录1、查看Nginx已编辑的模块2、Nginx官网查看内置模块3、停止Nginx服务4、Nginx

python urllib模块使用操作方法

《pythonurllib模块使用操作方法》Python提供了多个库用于处理URL,常用的有urllib、requests和urlparse(Python3中为urllib.parse),下面是这些... 目录URL 处理库urllib 模块requests 库urlparse 和 urljoin编码和解码

创建springBoot模块没有目录结构的解决方案

《创建springBoot模块没有目录结构的解决方案》2023版IntelliJIDEA创建模块时可能出现目录结构识别错误,导致文件显示异常,解决方法为选择模块后点击确认,重新校准项目结构设置,确保源... 目录创建spChina编程ringBoot模块没有目录结构解决方案总结创建springBoot模块没有目录

idea Maven Springboot多模块项目打包时90%的问题及解决方案

《ideaMavenSpringboot多模块项目打包时90%的问题及解决方案》:本文主要介绍ideaMavenSpringboot多模块项目打包时90%的问题及解决方案,具有很好的参考价值,... 目录1. 前言2. 问题3. 解决办法4. jar 包冲突总结1. 前言之所以写这篇文章是因为在使用Mav

Python标准库datetime模块日期和时间数据类型解读

《Python标准库datetime模块日期和时间数据类型解读》文章介绍Python中datetime模块的date、time、datetime类,用于处理日期、时间及日期时间结合体,通过属性获取时间... 目录Datetime常用类日期date类型使用时间 time 类型使用日期和时间的结合体–日期时间(