本指南介绍了如何识别和解决一些 JavaScript 问题,这些问题可能会导致您的网页(或 JavaScript 网页上的特定内容)无法显示在 Google 搜索结果中。虽然 Google 搜索可以运行 JavaScript,但您在设计网页和应用时需要考虑一些差异和限制,以顺应抓取工具访问和呈现您的内容的方式。我们的 JavaScript SEO 基础知识指南详细介绍了如何针对 Google 搜索优化 JavaScript 网站。
window.addEventListener('error',function(e){varerrorText=[e.message,'URL: '+e.filename,'Line: '+e.lineno+', Column: '+e.colno,'Stack: '+(e.error && e.error.stack||'(no stack trace)')].join('\n');// Example: log errors as visual output into the host page.// Note: you probably don't want to show such errors to users, or// have the errors get indexed by Googlebot; however, it may// be a useful feature while actively debugging the page.varDOM_ID='rendering-debug-pre';if(!document.getElementById(DOM_ID)){varlog=document.createElement('pre');log.id=DOM_ID;log.style.whiteSpace='pre-wrap';log.textContent=errorText;if(!document.body)document.body=document.createElement('body');document.body.insertBefore(log,document.body.firstChild);}else{document.getElementById(DOM_ID).textContent+='\n\n'+errorText;}// Example: log the error to remote service.// Note: you can log errors to a remote service, to understand// and monitor the types of errors encountered by regular users,// Googlebot, and other crawlers.varclient=newXMLHttpRequest();client.open('POST','https://example.com/logError');client.setRequestHeader('Content-Type','text/plain;charset=UTF-8');client.send(errorText);});
fetch(`https://api.kitten.club/cats/${id}`).then(res=>res.json()).then((cat)=>{if(!cat.exists){// redirect to page that gives a 404window.location.href='/not-found';}});
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-04。"],[[["\u003cp\u003eThis guide helps you identify and fix JavaScript issues that may be preventing your website content from appearing correctly in Google Search.\u003c/p\u003e\n"],["\u003cp\u003eUse the Rich Results Test or the URL Inspection Tool to see how Googlebot crawls and renders your web pages, including loaded resources, JavaScript errors, and the rendered DOM.\u003c/p\u003e\n"],["\u003cp\u003eEnsure your single-page application handles soft 404 errors correctly by redirecting to a 404 page or using the noindex meta tag for error pages.\u003c/p\u003e\n"],["\u003cp\u003eAvoid using URL fragments for loading content and rely on the History API instead, and ensure your web components render as expected by using the \u003ccode\u003e<slot>\u003c/code\u003e mechanism for light DOM content.\u003c/p\u003e\n"],["\u003cp\u003eGooglebot has limitations, such as declining permission requests and not supporting data persistence or connections like WebSockets and WebRTC, so design your content accordingly with fallbacks.\u003c/p\u003e\n"]]],["To resolve JavaScript-related search issues, first, test how Google crawls and renders your URLs using the Rich Results Test or URL Inspection Tool. Collect and audit JavaScript errors. Prevent soft 404 errors by redirecting or adding a \"noindex\" meta tag. Avoid relying on user permission requests, URL fragments, or data persistence. Employ content fingerprinting to avoid caching issues. Use feature detection for critical APIs, ensure HTTP connection compatibility, and verify web component rendering. Finally, retest your page after fixes.\n"],null,["Fix Search-related JavaScript problems\n\n\nThis guide helps you identify and fix JavaScript issues that may be blocking your page, or specific content on JavaScript powered pages, from showing up in Google Search.\nWhile Google Search does run JavaScript, there are some differences and limitations that you need to account for when designing your pages and applications to accommodate how crawlers access and render your content.\nOur [guide on JavaScript SEO basics](/search/docs/guides/javascript-seo-basics) has more information on how you can optimize your JavaScript site for Google Search.\n\nGooglebot is designed to be a good citizen of the web. Crawling is its [main priority](/search/blog/2017/01/what-crawl-budget-means-for-googlebot), while making sure it doesn't degrade the experience of users visiting the site.\nGooglebot and its Web Rendering Service (WRS) component continuously analyze and identify resources that don't contribute to essential page content and may not fetch such resources.\nFor example, reporting and error requests that don't contribute to essential page content, and other similar types of requests are unused or unnecessary to extract essential page content. Client-side analytics may not provide a full or accurate representation of Googlebot and WRS activity on your site.\nUse [the crawl stats report in Google Search Console](https://support.google.com/webmasters/answer/9679690) to monitor Googlebot and WRS activity and feedback on your site.\n\n\nIf you suspect that JavaScript issues might be blocking your page, or specific content on JavaScript powered pages, from showing up in Google Search, follow these steps. If you're not sure if JavaScript is the main cause, follow our [general debugging guide](/search/docs/guides/debug) to determine the specific issue.\n\n1. **To test how Google crawls and renders a URL** , use the [Rich Results Test](https://search.google.com/test/rich-results) or the [URL Inspection Tool](https://support.google.com/webmasters/answer/9012289) in Search Console. You can see loaded resources, JavaScript console output and exceptions, rendered DOM, and more information.\n\n\n Optionally, we also recommend collecting and auditing JavaScript errors encountered by users, including Googlebot, on your site to identify potential issues that may affect how content is rendered.\n Here's an example that shows how to log JavaScript errors that are logged in the [global onerror handler](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror). Note that some types of JavaScript errors, such as a parse error, cannot be logged with this method. \n\n ```javascript\n window.addEventListener('error', function(e) {\n var errorText = [\n e.message,\n 'URL: ' + e.filename,\n 'Line: ' + e.lineno + ', Column: ' + e.colno,\n 'Stack: ' + (e.error && e.error.stack || '(no stack trace)')\n ].join('\\n');\n\n // Example: log errors as visual output into the host page.\n // Note: you probably don't want to show such errors to users, or\n // have the errors get indexed by Googlebot; however, it may\n // be a useful feature while actively debugging the page.\n var DOM_ID = 'rendering-debug-pre';\n if (!document.getElementById(DOM_ID)) {\n var log = document.createElement('pre');\n log.id = DOM_ID;\n log.style.whiteSpace = 'pre-wrap';\n log.textContent = errorText;\n if (!document.body) document.body = document.createElement('body');\n document.body.insertBefore(log, document.body.firstChild);\n } else {\n document.getElementById(DOM_ID).textContent += '\\n\\n' + errorText;\n }\n\n // Example: log the error to remote service.\n // Note: you can log errors to a remote service, to understand\n // and monitor the types of errors encountered by regular users,\n // Googlebot, and other crawlers.\n var client = new XMLHttpRequest();\n client.open('POST', 'https://example.com/logError');\n client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');\n client.send(errorText);\n\n });\n ```\n2. **Make sure to prevent [`soft 404` errors](/search/docs/crawling-indexing/http-network-errors#soft-404-errors).** In a single-page application (SPA), this can be especially difficult. To prevent error pages from being indexed, you can use one or both of the following strategies:\n - Redirect to a URL where the server responds with a `404` status code. \n\n ```javascript\n fetch(`https://api.kitten.club/cats/${id}`)\n .then(res =\u003e res.json())\n .then((cat) =\u003e {\n if (!cat.exists) {\n // redirect to page that gives a 404\n window.location.href = '/not-found';\n }\n });\n ```\n - Add or change the robots `meta` tag to `noindex`. \n\n ```javascript\n fetch(`https://api.kitten.club/cats/${id}`)\n .then(res =\u003e res.json())\n .then((cat) =\u003e {\n if (!cat.exists) {\n const metaRobots = document.createElement('meta');\n metaRobots.name = 'robots';\n metaRobots.content = 'noindex';\n document.head.appendChild(metaRobots);\n }\n });\n ```\n\n\n When a SPA is using client-side JavaScript to handle errors they often report a `200` HTTP status code instead of the [appropriate status code](/search/docs/crawling-indexing/javascript/javascript-seo-basics#use-meaningful-http-status-codes). This can lead to error pages being indexed and possibly shown in search results.\n3. **Expect Googlebot to decline [user permission requests](https://w3c.github.io/permissions/#permission-registry).** \n Features that require user permission don't make sense for Googlebot, or for all users. For example, if you make the `Camera API` required, Googlebot can't provide a camera to you. Instead, provide a way for users to access your content without being forced to allow camera access.\n4. **Don't use URL fragments to load different content.** \n A SPA may use URL fragments (for example https://example.com/#/products) for loading different views. The [AJAX-crawling scheme has been deprecated](/search/blog/2015/10/deprecating-our-ajax-crawling-scheme) since 2015, so you can't rely on URL fragments to work with Googlebot. We recommend using the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History) to load different content based on the URL in a SPA.\n5. **Don't rely on data persistence to serve content.** \n WRS loads each URL (refer to [How Google Search Works](/search/docs/fundamentals/how-search-works) for an overview of how Google discovers content), following server and client redirects, same as a regular browser. However, WRS does not retain state across page loads:\n - Local Storage and Session Storage data are cleared across page loads.\n - HTTP Cookies are cleared across page loads.\n6. **Use content fingerprinting to avoid caching issues with Googlebot.** \n Googlebot caches aggressively in order to reduce network requests and resource usage. WRS may ignore caching headers. This may lead WRS to use outdated JavaScript or CSS resources. Content fingerprinting avoids this problem by making a fingerprint of the content part of the filename, like `main.2bb85551.js`. The fingerprint depends on the content of the file, so updates generate a different filename every time. Check out the [web.dev guide on long-lived caching strategies](https://web.dev/articles/http-cache#versioned-urls) to learn more.\n7. **Ensure that your application uses [feature detection](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection) for all critical APIs that it needs and provide a fallback behavior or polyfill where applicable.** \n Some web features may not yet be adopted by all user agents and some may intentionally disable certain features. For example, if you use WebGL to render photo effects in the browser, feature detection shows that Googlebot doesn't support WebGL. To fix this, you could skip the photo effect or decide to use server-side rendering to prerender the photo effects, which makes your content accessible to everyone, including Googlebot.\n8. **Make sure your content works with HTTP connections.** \n Googlebot uses HTTP requests to retrieve content from your server. It does not support other types of connections, such as [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) or [WebRTC](https://developer.mozilla.org/en-US/docs/Glossary/WebRTC) connections. To avoid problems with such connections, make sure to provide an HTTP fallback to retrieve content and use robust error handling and [feature detection](#feature-detection).\n9. **Make sure your web components render as expected.** Use the [Rich Results Test](https://search.google.com/test/rich-results) or the [URL Inspection Tool](https://support.google.com/webmasters/answer/9012289) to check if the rendered HTML has all content you expect. \n WRS flattens the [light DOM and shadow DOM](/web/fundamentals/web-components/shadowdom#lightdom). If the web components you use aren't using [`\u003cslot\u003e` mechanism](/web/fundamentals/web-components/shadowdom#slots) for light DOM content, consult the documentation of the web component for further information or use another web component instead. For more information, see [best practices for web components](/search/docs/guides/javascript-seo-basics#web-components).\n10. **After you fix the items in this checklist, test your page** with the [Rich Results Test](https://search.google.com/test/rich-results) or the [URL inspection tool](https://search.google.com/search-console) in Search Console again.\n\n If you fixed the issue, a green check mark appears and no errors display. If you still see errors, post in the [Search Central help community](https://support.google.com/webmasters/community)."]]