Zadbaj o dobrą organizację dzięki kolekcji Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Rozwiązywanie problemów z JavaScriptem związanych z wyszukiwarką
W tym przewodniku omawiamy, jak rozpoznać i rozwiązać problemy z JavaScriptem, przez które Twoja strona lub określone treści na stronach zapisanych w postaci kodu JavaScript mogą nie wyświetlać się w wyszukiwarce Google. Chociaż Google wykonuje kod JavaScript, podczas projektowania stron i aplikacji musisz wziąć pod uwagę pewne różnice i ograniczenia, aby roboty mogły uzyskać dostęp do Twoich treści i je wyrenderować. Nasz przewodnik po podstawach SEO JavaScriptu zawiera więcej informacji na temat optymalizacji witryny utworzonej przy użyciu JavaScriptu pod kątem wyszukiwarki Google.
Googlebot został zaprojektowany z myślą o sprawnym funkcjonowaniu w internecie. Jego głównym priorytetem jest indeksowanie stron bez obniżania komfortu użytkowników witryny. Googlebot, wykorzystując usługę renderowania sieciowego (WRS), stale analizuje i identyfikuje zasoby, które nie mają wpływu na istotne treści strony, i może ich nie pobierać. Na przykład żądania związane z raportowaniem i błędami, które nie są istotnym elementem zawartości strony, i inne podobne typy żądań nie są używane ani konieczne do wyodrębnienia najważniejszych treści na stronie. Analiza po stronie klienta może przedstawiać działania Googlebota i WRS w witrynie w sposób niepełny lub niedokładny. Aby monitorować te działania oraz opinie dotyczące Twojej witryny, użyj raportu Statystyki indeksowania w Google Search Console.
Jeśli podejrzewasz, że przez problemy z JavaScriptem Twoja strona lub określone treści na stronach zapisanych w postaci kodu JavaScript mogą nie wyświetlać się w wyszukiwarce Google, wykonaj te czynności: Jeśli nie masz pewności, czy główną przyczyną błędu jest JavaScript, postępuj zgodnie z naszym ogólnym przewodnikiem na temat debugowania, aby znaleźć źródło problemu.
- Aby sprawdzić, w jaki sposób Google indeksuje i renderuje URL, przeprowadź test wyników z elementami rozszerzonymi lub użyj narzędzia do sprawdzania adresów URL w Search Console. Możesz zobaczyć m.in. załadowane zasoby, dane wyjściowe i wyjątki konsoli JavaScript oraz wyrenderowane DOM.
Opcjonalnie zalecamy też rejestrowanie i kontrolowanie błędów JavaScriptu wykrytych przez użytkowników, w tym Googlebota, w witrynie, aby rozpoznać potencjalne problemy, które mogą wpływać na sposób renderowania treści. Oto przykład, który ilustruje, jak zarejestrować błędy JavaScriptu odnotowane w globalnym module obsługi właściwości onerror. Uwaga: niektórych typów błędów JavaScriptu (np. błędów analizy) nie można rejestrować tą metodą.
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); });
- Pamiętaj, aby zapobiegać błędom
soft 404
. Może to być szczególnie trudne w aplikacji jednostronicowej. Aby uniknąć indeksowania stron z błędami, skorzystaj z jednej lub obu tych strategii: - Utwórz przekierowanie do adresu URL, pod którym serwer odpowiada kodem stanu
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'; } });
- Dodaj lub zmień tag
meta
robots na 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); } });
Gdy aplikacja jednostronicowa używa JavaScriptu po stronie klienta do obsługi błędów, często zamiast odpowiedniego kodu stanu zgłasza kod stanu HTTP 200
. W efekcie strony błędów mogą być indeksowane i wyświetlane w wynikach wyszukiwania.
- Googlebot prawdopodobnie odrzuci prośby o zgodę użytkownika.
Funkcje, które wymagają zgody użytkownika, nie sprawdzają się w przypadku Googlebota ani wszystkich użytkowników. Jeśli na przykład wymagany jest interfejs Camera API
, Googlebot nie może udostępnić Ci aparatu. Zamiast tego zadbaj, żeby użytkownicy mogli uzyskiwać dostęp do treści w sposób, który nie wiąże się z koniecznością zezwolenia na dostęp do aparatu. - Nie używaj fragmentów adresów URL w celu wczytywania różnych treści.
Do wczytywania różnych widoków aplikacja jednostronicowa może używać adresów URL z fragmentami (np. https://example.com/#/products). Schemat indeksowania AJAX został wycofany w 2015 r., więc adresy URL z fragmentami nie będą współdziałać z Googlebotem. Do wczytywania różnych treści na podstawie adresu URL w aplikacji jednostronicowej zalecamy używanie interfejsu History API. - Trwałość danych nie gwarantuje prawidłowego wyświetlania treści.
WRS ładuje każdy URL, podążając za przekierowaniami serwerów i klientów tak samo jak zwykła przeglądarka (odkrywanie treści przez Google omówiliśmy w przewodniku Jak działa wyszukiwarka Google). WRS nie zachowuje jednak informacji o stanie po wczytaniu stron: - Dane pamięci lokalnej i pamięci sesji są usuwane po wczytaniu stron.
- Pliki cookie HTTP są usuwane po wczytaniu stron.
- Aby w przypadku Googlebota uniknąć problemów z buforowaniem, używaj odcisków cyfrowych treści.
Googlebot intensywnie korzysta z pamięci podręcznej, aby zmniejszać liczbę żądań sieciowych i obciążenie zasobów. WRS może ignorować nagłówki zapisu w pamięci podręcznej. Może to prowadzić do korzystania przez WRS z nieaktualnych zasobów JavaScriptu lub CSS-u. Uniknąć tego problemu pozwala odcisk cyfrowy treści umieszczany we fragmencie nazwy pliku odnoszącym się do treści, np. main.2bb85551.js
. Odcisk cyfrowy zależy od zawartości pliku, więc jej aktualizacje powodują każdorazowe utworzenie innej nazwy pliku. Więcej informacji znajdziesz w przewodniku web.dev po strategiach długiego buforowania. - Sprawdź, czy Twoja aplikacja korzysta z wykrywania funkcji w przypadku wszystkich krytycznych interfejsów API, których potrzebuje, i w razie potrzeby zapewnij zachowanie rezerwowe lub kod polyfill.
Być może jeszcze nie wszystkie klienty użytkownika korzystają z niektórych funkcji sieciowych. Z kolei niektóre klienty mogły celowo wyłączyć wybrane funkcje. Jeśli na przykład używasz WebGL do renderowania efektów fotograficznych w przeglądarce, wykrywanie funkcji pokazuje, że Googlebot nie obsługuje WebGL. Aby to naprawić, możesz pominąć efekt fotograficzny lub zdecydować się na renderowanie po stronie serwera, aby wstępnie renderować efekty fotograficzne. Dzięki temu Twoje treści będą dostępne dla wszystkich, w tym dla Googlebota. - Upewnij się, że Twoje treści obsługują połączenia HTTP.
Googlebot pobiera treści z Twojego serwera za pomocą żądań HTTP. Nie obsługuje innych typów połączeń, np. WebSockets
ani WebRTC
. Aby uniknąć problemów z takimi połączeniami, zadbaj o możliwość zastępczego pobierania treści przez HTTP oraz korzystaj z niezawodnych metod obsługi błędów i wykrywania funkcji. - Upewnij się, że komponenty sieciowe są renderowane zgodnie z oczekiwaniami. Aby sprawdzić, czy wyrenderowany HTML ma całą oczekiwaną zawartość, użyj testu wyników z elementami rozszerzonymi lub narzędzia do sprawdzania adresów URL.
WRS spłaszcza modele Light DOM i Shadow DOM. Jeśli komponenty internetowe, których używasz, nie korzystają z mechanizmu <slot>
na potrzeby zawartości modelu Light DOM, poszukaj dodatkowych informacji w dokumentacji danego komponentu internetowego lub użyj innego komponentu internetowego. Aby uzyskać więcej informacji, zapoznaj się ze sprawdzonymi metodami korzystania z komponentów internetowych. - Gdy przejrzysz tę listę kontrolną i wprowadzisz odpowiednie zmiany, jeszcze raz przetestuj stronę za pomocą testu wyników z elementami rozszerzonymi lub narzędzia do sprawdzania adresów URL w Search Console.
Jeśli problem został rozwiązany, pojawia się zielony znacznik wyboru i nie wyświetlają się żadne błędy. Jeśli nadal widzisz błędy, opublikuj posta na Forum pomocy Centrum wyszukiwarki.
O ile nie stwierdzono inaczej, treść tej strony jest objęta licencją Creative Commons – uznanie autorstwa 4.0, a fragmenty kodu są dostępne na licencji Apache 2.0. Szczegółowe informacje na ten temat zawierają zasady dotyczące witryny Google Developers. Java jest zastrzeżonym znakiem towarowym firmy Oracle i jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-08-04 UTC.
[null,null,["Ostatnia aktualizacja: 2025-08-04 UTC."],[[["\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)."]]