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通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

Python logging模块使用示例详解

《Pythonlogging模块使用示例详解》Python的logging模块是一个灵活且强大的日志记录工具,广泛应用于应用程序的调试、运行监控和问题排查,下面给大家介绍Pythonlogging模... 目录一、为什么使用 logging 模块?二、核心组件三、日志级别四、基本使用步骤五、快速配置(bas

Python datetime 模块概述及应用场景

《Pythondatetime模块概述及应用场景》Python的datetime模块是标准库中用于处理日期和时间的核心模块,本文给大家介绍Pythondatetime模块概述及应用场景,感兴趣的朋... 目录一、python datetime 模块概述二、datetime 模块核心类解析三、日期时间格式化与

Python如何调用指定路径的模块

《Python如何调用指定路径的模块》要在Python中调用指定路径的模块,可以使用sys.path.append,importlib.util.spec_from_file_location和exe... 目录一、sys.path.append() 方法1. 方法简介2. 使用示例3. 注意事项二、imp

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模