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利用自带模块实现屏幕像素高效操作

《Python利用自带模块实现屏幕像素高效操作》这篇文章主要为大家详细介绍了Python如何利用自带模块实现屏幕像素高效操作,文中的示例代码讲解详,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、获取屏幕放缩比例2、获取屏幕指定坐标处像素颜色3、一个简单的使用案例4、总结1、获取屏幕放缩比例from

nginx-rtmp-module模块实现视频点播的示例代码

《nginx-rtmp-module模块实现视频点播的示例代码》本文主要介绍了nginx-rtmp-module模块实现视频点播,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录预置条件Nginx点播基本配置点播远程文件指定多个播放位置参考预置条件配置点播服务器 192.

多模块的springboot项目发布指定模块的脚本方式

《多模块的springboot项目发布指定模块的脚本方式》该文章主要介绍了如何在多模块的SpringBoot项目中发布指定模块的脚本,作者原先的脚本会清理并编译所有模块,导致发布时间过长,通过简化脚本... 目录多模块的springboot项目发布指定模块的脚本1、不计成本地全部发布2、指定模块发布总结多模

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Node.js 中 http 模块的深度剖析与实战应用小结

《Node.js中http模块的深度剖析与实战应用小结》本文详细介绍了Node.js中的http模块,从创建HTTP服务器、处理请求与响应,到获取请求参数,每个环节都通过代码示例进行解析,旨在帮... 目录Node.js 中 http 模块的深度剖析与实战应用一、引言二、创建 HTTP 服务器:基石搭建(一

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit

Python模块导入的几种方法实现

《Python模块导入的几种方法实现》本文主要介绍了Python模块导入的几种方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录一、什么是模块?二、模块导入的基本方法1. 使用import整个模块2.使用from ... i

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参数