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: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

Jenkins构建Maven聚合工程,指定构建子模块

一、设置单独编译构建子模块 配置: 1、Root POM指向父pom.xml 2、Goals and options指定构建模块的参数: mvn -pl project1/project1-son -am clean package 单独构建project1-son项目以及它所依赖的其它项目。 说明: mvn clean package -pl 父级模块名/子模块名 -am参数

寻迹模块TCRT5000的应用原理和功能实现(基于STM32)

目录 概述 1 认识TCRT5000 1.1 模块介绍 1.2 电气特性 2 系统应用 2.1 系统架构 2.2 STM32Cube创建工程 3 功能实现 3.1 代码实现 3.2 源代码文件 4 功能测试 4.1 检测黑线状态 4.2 未检测黑线状态 概述 本文主要介绍TCRT5000模块的使用原理,包括该模块的硬件实现方式,电路实现原理,还使用STM32类

UVM:callback机制的意义和用法

1. 作用         Callback机制在UVM验证平台,最大用处就是为了提高验证平台的可重用性。在不创建复杂的OOP层次结构前提下,针对组件中的某些行为,在其之前后之后,内置一些函数,增加或者修改UVM组件的操作,增加新的功能,从而实现一个环境多个用例。此外还可以通过Callback机制构建异常的测试用例。 2. 使用步骤         (1)在UVM组件中内嵌callback函

python内置模块datetime.time类详细介绍

​​​​​​​Python的datetime模块是一个强大的日期和时间处理库,它提供了多个类来处理日期和时间。主要包括几个功能类datetime.date、datetime.time、datetime.datetime、datetime.timedelta,datetime.timezone等。 ----------动动小手,非常感谢各位的点赞收藏和关注。----------- 使用datet

C8T6超绝模块--EXTI

C8T6超绝模块–EXTI 大纲 控制流程结构体分析EXTI实现按键 具体案例 控制流程 这里是流程框图,具体可以去看我STM32专栏的EXTI的具体分析 结构体分析 typedef struct {uint32_t EXTI_Line; // 中断/事件线EXTIMode_TypeDef EXTI_Mode; // EXTI 模式EXTITrigger_TypeDef EXTI_

1、创建多模块的maven springboot项目

现在的java的项目都是多模块的,这次也跟个风。 目标:实现下述结构 项目AcedBoot, 子模块:         aced-api 对外提供接口,         aced-web 给前端提供接口,         aced-service 服务层,         aced-dao 数据底层,包含数据库mapper和实体类entity,         aced-commo

Vue2电商项目(二) Home模块的开发;(还需要补充js节流和防抖的回顾链接)

文章目录 一、Home模块拆分1. 三级联动组件TypeNav2. 其余组件 二、发送请求的准备工作1. axios的二次封装2. 统一管理接口API----跨域3. nprogress进度条 三、 vuex模块开发四、TypeNav三级联动组件开发1. 动态展示三级联动数据2. 三级联动 动态背景(1)、方式一:CSS样式(2)、方式二:JS 3. 控制二三级数据隐藏与显示--绑定styl

PrestaShop免费模块/插件/扩展/工具下载

PrestaShop免费模块/插件/扩展/工具下载 PrestaShop免费模块 适用于您的电子商务网站的PrestaShop模块 现有超过3,000个PrestaShop模块可帮助您自定义在线商店,增加流量,提高转化率并建立客户忠诚度。 使您的电子商务网站成功! 下载(超过142+之多的PrestaShop官网认证的免费模块) 标签PrestaShop免费, PrestaShop免费工