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.');
  // Decorate
  newPage.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 path
    networkRequest.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);
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值