Googlebot是否将空字符串视为真值?JS错误追踪代码异常排查
Let's break down this confusing edge case—your logic looks solid on paper, so this is likely a quirk in how Googlebot's rendering engine handles JavaScript error events.
First, let's recap your exclusion condition:
if (!event.filename || !event.filename.includes("mywebsite.com")) { return; // Skip non-site errors }
The idea is: if the filename is falsy (empty string, undefined, etc.) OR it doesn't match your domain, we ignore the error. An empty string should trigger the first part of the condition (!event.filename evaluates to true) and skip the report—so why isn't that happening with Googlebot?
The Most Likely Cause
Googlebot's crawler uses a modified JavaScript engine that sometimes deviates from standard behavior. Here's what's probably going on:
event.filenameisn't a primitive empty string
In normal JS, a primitive empty string""is falsy, so!""returnstrue. But if Googlebot is settingevent.filenameto a wrappedStringobject (likenew String("")) instead of a primitive, things change:
All objects in JS are truthy, even if their content is empty. So!new String("")would returnfalse, skipping the first check. Whileevent.filename.includes("mywebsite.com")would still returnfalse(making!falseequal totrue), it’s possible Googlebot’s engine handles this combination of object type and empty content in an unexpected way that slips through your original condition.Log representation vs. actual value mismatch
Maybe what you're seeing as an empty string in your error reports isn't really a primitive"". For example, it could be a string with invisible whitespace (like a single space or null character). Those are truthy in JS, so!event.filenamewould befalse—but this still should trigger the second part of your condition. However, it’s worth verifying the raw value in your logs to rule this out.
A Robust Fix
To cover this edge case (and any other weird crawler quirks), rewrite your logic to explicitly validate the filename instead of relying on implicit truthiness:
window.addEventListener('error', function(event) { if (!window.XMLHttpRequest && !window.JSON) { return; } // Only report errors with valid, non-empty filenames from your site const isValidFilename = typeof event.filename === 'string' && event.filename.trim() !== "" && event.filename.includes("mywebsite.com"); if (!isValidFilename) { return; } var httpRequest = new XMLHttpRequest(); httpRequest.open('POST', '/post-js-error', true); httpRequest.setRequestHeader('Content-Type', 'application/json'); httpRequest.send(JSON.stringify(event)); });
This approach:
- Checks that
event.filenameis actually a string (not an object or other type) - Ensures it's not empty or just whitespace
- Confirms it contains your domain
By being explicit, you eliminate ambiguity that crawler-specific JS engines might exploit.
内容的提问来源于stack exchange,提问作者apflieger

