Capturing page script errors

Errors that are generated within the scripts that are coded within the page.evaluate method will not trigger phantom.onError; however, the webpage object's onError callback will receive the event instead. The definition of the function is the same, except that we define our handling on the webpage instance as shown in the following code:

var page = require('webpage').create();
page.onError = function(msg, trace) {
  console.log(msg);
  if (trace) {
    trace.forEach(function(t) {
      var stackmsg = '  at' + (t.function ? ' function ' + t.function : '') + ' (' + (t.file || t.sourceURL) + ':' + t.line + ')';
      console.log(stackmsg);
    });
  }
};

Assume that we have the following code in our webpage evaluate block:

page.open(url, function(status) {
  page.evaluate(function() {
    documentx.content = 1;
  });
});

As we see in the preceding code, we have a reference to an object named documentx, which is an invalid object since there is no such object within the page (see page1.html of the following code).

<html>
  <head>
    <title>Page 1</title>
  </head>
  <body>
    <h1>Page 1</h1>
    <a href='page2.htm' id='page2'>Go to Page 2</a>
  </body>
</html>

When we execute this script, it will generate an error and call the page.onError handling. The phantom object definition will not be called since it is beyond the scope of the webpage object, as shown in the following screenshot:

Capturing page script errors

Since the documentx object is unknown, it will generate a reference error stating that the variable cannot be found. This error handling is not limited to the evaluate block codes. This callback will also receive error events if the page being referenced contains JavaScript errors.

Let us say we have pagex.htm and that the following will be the HTML source:

<html>
  <head>
    <title>Page X</title>
    <script>
      $('#not_an_element').show();
    </script>
  </head>
  <body>
    <h1>Page X</h1>
  </body>
</html>

In the preceding code, we have a JavaScript code that uses a third-party library syntax, which we did not include previously; because of this, the syntax is not recognized and will generate an error upon loading the page. Running our preceding script and loading pagex.htm will show the output shown in the following screenshot:

Capturing page script errors
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.240.210