2
votes

How do I properly do object detection for window.performance.timing?

An unknown version of Chrome being run by Googlebot is spawning the following error:

Uncaught TypeError: Cannot read property 'timing' of undefined

The only instances of window.performance.timing are in the following snippets of code:

else if (
window.performance!=undefined
&& window.performance.timing!=undefined
&& window.performance.timing.toJSON!=undefined) {/* etc */}

Obviously regardless of my efforts to do object detection Googlebot is somehow still spawning the error message. I can not use try and catch and I have zero instances in my JavaScript error log of this happening in any testable (e.g. Chrome itself) browser, only Googlebot.

3
Have you tried taking out the != undefined part, and just doing "else if (window.performance && window.performance.timing && " etc.? - John D.
This code works as expected: jsfiddle.net/x3373vm5 . If window.performance is undefined, it would not try to access window.performance.timing. The error must originate from somewhere else. - Felix Kling
The problem is probably in /* etc */. :) The error message usually tells you the line number in your code. - Thevs
By the way, if it's a bot - have you tried to check the window object? - Thevs
@FelixKling - The first line of your jsfiddle sets window.performance = undefined... If that line is removed, the test fails - jsfiddle.net/v7zvvqoq/1 - dana

3 Answers

0
votes

Try this way.

else if (
window.performance
&& window.performance.timing
&& window.performance.timing.toJSON) {/* etc */}

And as I know, you should use !== instead of !=

0
votes

If window.performanceis undefined the if statement will still check the other two expressions. If there is no window.performance it can't check for window.performance.timing.

At least that's what I am guessing. I would try to nest the if statements:

if(window.performance != undefined) {
  if(window.performance.timing != undefined) {
    if(window.performance.timing.toJSON != undefined) {
      /* etc */
    }
  }
}
-1
votes

What if window.performance is null? I bet you would get the same error message.

That's why the canonical way to check objects existence is:

if (window.performance && window.performance.whatever && ...) ...