使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。
解决与 Google 搜索相关的 JavaScript 问题
本指南介绍了如何识别和解决一些 JavaScript 问题,这些问题可能会导致您的网页(或 JavaScript 网页上的特定内容)无法显示在 Google 搜索结果中。虽然 Google 搜索可以运行 JavaScript,但您在设计网页和应用时需要考虑一些差异和限制,以顺应抓取工具访问和呈现您的内容的方式。我们的 JavaScript SEO 基础知识指南详细介绍了如何针对 Google 搜索优化 JavaScript 网站。
Googlebot 经过精心设计,是一名优秀的网上公民。它的主要任务是抓取网站,同时确保其抓取操作不会导致网站的用户体验下降。Googlebot 及其网页渲染服务 (WRS) 组件会不断分析和识别对基本网页内容没有贡献的资源,并且可能不会抓取此类资源。例如,对基本网页内容没有贡献的报告和错误请求,以及在提取基本网页内容时不使用或没必要使用的其他类似类型的请求。客户端分析可能无法完整或准确地体现您网站上的 Googlebot 和 WRS 活动。使用 Google Search Console 中的“抓取统计信息”报告可监控您网站上的 Googlebot 和 WRS 活动及反馈。
如果您怀疑 JavaScript 问题可能会导致您的网页或 JavaScript 网页上的特定内容无法显示在 Google 搜索结果中,请按以下步骤操作。如果您不确定 JavaScript 是否是主要原因,请按照我们的一般调试指南确定具体问题。
- 如需测试 Google 抓取和渲染网址的效果,请使用 Search Console 中的富媒体搜索结果测试或网址检查工具。您可以查看已加载的资源、JavaScript 控制台输出和异常、渲染的 DOM 以及更多信息。
此外,我们还建议您收集和审核用户(包括 Googlebot)在您网站上遇到的 JavaScript 错误,确定可能会影响内容渲染效果的潜在问题。 以下示例演示了如何记录全局 onerror 处理程序中记录的 JavaScript 错误。请注意,某些类型的 JavaScript 错误(如解析错误)无法使用此方法进行记录。
window.addEventListener('error', function(e) { var errorText = [ 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. var DOM_ID = 'rendering-debug-pre'; if (!document.getElementById(DOM_ID)) { var log = 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. var client = new XMLHttpRequest(); client.open('POST', 'https://example.com/logError'); client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); client.send(errorText); });
- 请务必防范
soft 404
错误。 在单页应用 (SPA) 中,这可能会非常困难。 为防止将错误网页编入索引,您可以使用以下一种或两种策略: - 重定向至服务器响应
404
状态代码的网址。 fetch(`https://api.kitten.club/cats/${id}`) .then(res => res.json()) .then((cat) => { if (!cat.exists) { // redirect to page that gives a 404 window.location.href = '/not-found'; } });
- 添加 robots
meta
标记或将其更改为 noindex
。 fetch(`https://api.kitten.club/cats/${id}`) .then(res => res.json()) .then((cat) => { if (!cat.exists) { const metaRobots = document.createElement('meta'); metaRobots.name = 'robots'; metaRobots.content = 'noindex'; document.head.appendChild(metaRobots); } });
SPA 使用客户端 JavaScript 处理错误时,通常会报告 200
HTTP 状态代码,而不是相应的状态代码。 这会导致错误网页被编入索引并可能会显示在搜索结果中。
- Googlebot 可能会拒绝用户权限请求。
需要用户权限的功能不适用于 Googlebot 或所有用户。例如,如果您需要 Camera API
,而 Googlebot 无法向您提供相机。在这种情况下,应为用户提供一种方式,使其无需授予相机访问权限便能访问您的内容。 - 请勿使用网址片段加载不同的内容。
SPA 可能会使用网址片段(例如 https://example.com/#/products)加载不同的视图。自 2015 年起,我们已弃用 AJAX 抓取方案,因此您不能提供网址片段让 Googlebot 抓取。我们建议您使用 History API,以根据 SPA 中的网址加载不同的内容。 - 不要依赖数据持久性来提供内容。
和常规浏览器一样,WRS 会加载每个网址(请参阅 Google 搜索的工作原理,简要了解 Google 如何发现内容),并执行服务器和客户端重定向。不过,在网页加载过程中,WRS 不会保留状态: - 在网页加载过程中,系统会清除本地存储空间和会话存储空间中的数据。
- 在网页加载过程中,系统会清除 HTTP Cookie。
- 使用内容指纹避免 Googlebot 缓存问题。
Googlebot 会主动缓存内容,以减少网络请求和资源使用量。WRS 可能会忽略缓存标头。这可能会导致 WRS 使用过时的 JavaScript 或 CSS 资源。为了避免这个问题,您可以创建内容指纹,使其成为文件名的一部分(如 main.2bb85551.js
)。 指纹取决于文件的内容,因此每次更新都会生成不同的文件名。如需了解详情,请参阅 web.dev 长效缓存策略指南。 - 确保您的应用针对其所需的所有关键 API 使用功能检测,并在适用情况下提供后备行为或 polyfill。
某些网页功能可能不会被所有用户代理采用,而一些用户代理可能会刻意停用特定功能。例如,如果您在浏览器中使用 WebGL 渲染照片效果,功能检测会显示 Googlebot 不支持 WebGL。若要修复此问题,您可以跳过照片效果渲染步骤或使用服务器端渲染来预渲染照片效果,这样一来,所有用户(包括 Googlebot)都可访问您的内容。 - 确保您的内容适用于 HTTP 连接。
Googlebot 会使用 HTTP 请求从您的服务器检索内容。它不支持其他类型的连接,例如 WebSockets
或 WebRTC
连接。为避免此类连接出现问题,请务必提供用于检索内容的 HTTP 回退机制,并使用强大的错误处理和功能检测机制。 - 确保网络组件能按预期呈现。 使用富媒体搜索结果测试或网址检查工具检查渲染的 HTML 是否包含您期望的所有内容。
WRS 会扁平化 light DOM 和 shadow DOM。如果您使用的网络组件没有针对 light DOM 内容使用 <slot>
机制,请参阅相应网络组件的文档以了解详情,或使用其他网络组件。如需了解详情,请参阅网络组件最佳做法。 - 修正此核对清单中的内容后,请再次使用 Search Console 中的富媒体搜索结果测试或网址检查工具测试您的网页。
如果问题已解决,系统会显示一个绿色对勾标记,并且不会显示任何错误。如果您仍看到错误,请在 Google 搜索中心帮助社区中发帖咨询。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-04。
[null,null,["最后更新时间 (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)."]]