Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Gerar dados estruturados com JavaScript
Os sites modernos usam JavaScript para exibir muitos conteúdos dinâmicos. Há
algumas considerações importantes ao usar JavaScript para gerar dados estruturados nos seus
sites. Este guia aborda as práticas recomendadas e estratégias de implementação. Caso você não saiba
muito sobre o assunto, veja
como os dados estruturados funcionam.
Existem várias maneiras de gerar dados estruturados com JavaScript, mas estas são as mais comuns:
Usar o Gerenciador de tags do Google para gerar JSON-LD dinamicamente
O Gerenciador de tags do Google é uma plataforma que permite gerenciar as tags do site sem editar o código. Para gerar dados estruturados com o Gerenciador de tags do Google, siga estas etapas:
Como usar variáveis no Gerenciador de tags do Google
O Gerenciador de tags do Google (GTM) é compatível com variáveis
para usar informações da página como parte dos dados estruturados. Use variáveis para extrair
os dados estruturados da página em vez de duplicar as informações no GTM. A duplicação aumenta
o risco de incompatibilidade entre o conteúdo da página e os dados estruturados inseridos via GTM.
Por exemplo, você pode criar dinamicamente
um bloco de receita em JSON-LD
que usa o título da página como o nome da receita, criando a seguinte variável personalizada chamada
recipe_name:
function(){returndocument.title;}
Em seguida, use {{recipe_name}} na sua tag HTML personalizada.
Recomendamos criar variáveis para coletar todas as informações necessárias da página.
Veja um exemplo de conteúdo da tag HTML personalizada:
Gerar dados estruturados com JavaScript personalizado
Outra forma de gerar dados estruturados é usar JavaScript para gerar todos
os dados ou adicionar informações ao que foi renderizado no servidor. De qualquer forma,
a Pesquisa Google é capaz de compreender e processar dados estruturados disponíveis no DOM ao
renderizar a página. Para saber mais sobre como a Pesquisa Google processa a linguagem, veja o
guia básico de JavaScript.
Veja um exemplo de dados estruturados gerados por JavaScript:
Edite o HTML do site para incluir um snippet JavaScript como o exemplo a seguir. Consulte
a documentação do seu provedor de hospedagem ou CMS (sistema de gerenciamento de conteúdo), ou pergunte aos desenvolvedores.
Sucesso: se você fizer tudo corretamente, e o tipo de dados estruturados for compatível com a ferramenta, você vai ver a mensagem "A página está qualificada para pesquisa aprimorada". Se você estiver testando um tipo de dados estruturados que não é compatível com o teste de pesquisa aprimorada, confira o HTML renderizado.
Se o HTML renderizado conter os dados estruturados, a Pesquisa Google poderá processá-los.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-04 UTC."],[[["\u003cp\u003eThis guide provides best practices for implementing structured data with JavaScript on your website to enhance search engine understanding.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Tag Manager and custom JavaScript code are the primary methods for dynamically generating structured data.\u003c/p\u003e\n"],["\u003cp\u003eWhen using JavaScript, ensure your server has enough resources to handle potential increased traffic from Google, especially with \u003ccode\u003eProduct\u003c/code\u003e markup.\u003c/p\u003e\n"],["\u003cp\u003eValidate your structured data implementation using the Rich Results Test to identify and resolve any errors or warnings.\u003c/p\u003e\n"],["\u003cp\u003eRefer to the comprehensive structured data documentation and JavaScript troubleshooting guide for detailed information and support.\u003c/p\u003e\n"]]],["JavaScript dynamically generates website content and structured data through methods like Google Tag Manager (GTM) or custom JavaScript. GTM allows adding structured data via Custom HTML tags and using variables to avoid data duplication. Custom JavaScript can generate or augment structured data, which becomes available in the DOM. Server-side rendering can also include structured data. Implementation should be validated with the Rich Results Test, ensuring the data is crawlable and indexable by Google Search.\n"],null,["# Generate Structured Data with JavaScript | Google Search Central\n\nGenerate structured data with JavaScript\n========================================\n\nModern websites use JavaScript to display lots of dynamic content. There are a\nfew things you need to look out for when using JavaScript to generate structured data on your\nwebsites, and this guide covers best practices and implementation strategies. If you're new to\nstructured data, you can learn more about\n[how structured data works](/search/docs/appearance/structured-data/intro-structured-data).\n\nThere are different ways to generate structured data with JavaScript, but the most common are:\n\n- [Google Tag Manager](#use-google-tag-manager)\n- [Custom JavaScript](#custom-javascript)\n\n| **Using `Product` markup?** Be aware that dynamically-generated markup can make Shopping crawls less frequent and less reliable, which can be an issue for fast-changing content like product availability and price. If you're a merchant optimizing for all types of shopping results, make sure your server has enough computing resources to handle increased traffic from Google.\n\nUse Google Tag Manager to generate JSON-LD dynamically\n------------------------------------------------------\n\n[Google Tag Manager](https://tagmanager.google.com/) is a\nplatform that lets you manage tags on your website without editing the code. To generate structured\ndata with Google Tag Manager, follow these steps:\n\n1. [Set up and install Google Tag Manager](https://support.google.com/tagmanager/answer/6103696) on your site.\n2. Add a new **Custom HTML** tag to the container.\n3. Paste a [supported structured data](/search/docs/guides/search-gallery) block into the tag content.\n4. Install the container as shown in the **Install Google Tag Manager** section of your container's admin menu.\n5. To add the tag to your website, publish your container in the Google Tag Manager interface.\n6. [Test your implementation](#testing).\n\n### Using variables in Google Tag Manager\n\nGoogle Tag Manager (GTM) supports [variables](https://support.google.com/tagmanager/topic/7683268?ref_topic=3441647)\nto use information on the page as part of your structured data. Use variables to extract\nthe structured data from the page instead of duplicating the information in GTM. Duplicating the information in GTM increases\nthe risk of having a mismatch between page content and the structured data inserted using GTM.\n\nFor example, you can dynamically create\na [Recipe](/search/docs/appearance/structured-data/recipe) JSON-LD block\nthat uses the page title as the recipe name by creating the following custom variable named\n`recipe_name`: \n\n```javascript\nfunction() { return document.title; }\n```\n\nYou can then use `{{recipe_name}}` in your custom tag HTML.\n\nWe recommend to create variables to collect all the necessary information from the page using variables.\n\nHere is an example for the custom HTML tag content: \n\n```javascript\n\u003cscript type=\"application/ld+json\"\u003e\n {\n \"@context\": \"https://schema.org/\",\n \"@type\": \"Recipe\",\n \"name\": \"{{recipe_name}}\",\n \"image\": [ \"{{recipe_image}}\" ],\n \"author\": {\n \"@type\": \"Person\",\n \"name\": \"{{recipe_author}}\"\n }\n }\n\u003c/script\u003e\n```\n| **Note:** The previous sample assumes that you defined the variables `recipe_name`, `recipe_image` and `recipe_author` in GTM.\n\nGenerate structured data with custom JavaScript\n-----------------------------------------------\n\nAnother way you can generate structured data is by using JavaScript to either generate all of\nyour structured data or add more information to the server-side rendered structured data. Either way,\nGoogle Search can understand and process structured data that's available in the DOM when it\nrenders the page. To learn more about how Google Search processes JavaScript, check out the\n[JavaScript basics guide](/search/docs/crawling-indexing/javascript/javascript-seo-basics).\n\nHere is an example of JavaScript-generated structured data:\n\n1. [Find the type of\n structured data](/search/docs/appearance/structured-data/search-gallery) you are interested in.\n2. Edit your website's HTML to include a JavaScript snippet like the following example (refer to the documentation from your CMS or hosting provider, or ask your developers). \n\n ```javascript\n fetch('https://api.example.com/recipes/123')\n .then(response =\u003e response.text())\n .then(structuredDataText =\u003e {\n const script = document.createElement('script');\n script.setAttribute('type', 'application/ld+json');\n script.textContent = structuredDataText;\n document.head.appendChild(script);\n });\n ```\n3. [Test your implementation with the Rich Results Test](#testing).\n\nUsing server-side rendering\n---------------------------\n\nIf you are using [server-side rendering](/web/updates/2019/02/rendering-on-the-web#server-rendering),\nyou can also include the structured data in the rendered output. Check the documentation\nof your framework to find out how to generate the JSON-LD for [the type of structured data](/search/docs/appearance/structured-data/search-gallery)\nyou're interested in.\n\nTest your implementation\n------------------------\n\nTo make sure Google Search can crawl and index your structured data, test your implementation:\n\n1. Open the [Rich Results Test](https://goo.gle/richresults).\n2. Enter the URL that you want to test. We recommend that you use the URL input instead of the code input because there are JavaScript limitations when using the code input (for example, CORS restrictions).\n3. Click **Test URL** .\n\n **Success** : If you did everything correctly and your [structured data type is supported in the tool](https://support.google.com/webmasters/answer/7445569),\n you will see the message \"Page is eligible for rich results\". \n\n If you are testing a structured data type that is not supported by the Rich Results test, check the rendered HTML.\n If the rendered HTML contains the structured data, Google Search will be able to process it.\n\n **Try again** : If you see errors or warnings, it is most likely a syntax error or a missing property.\n Read the [documentation\n for your type of structured data](/search/docs/appearance/structured-data/search-gallery) and make sure you've added all the properties. If your problem\n persists, make sure to also check the guide on [fixing search-related JavaScript problems](/search/docs/crawling-indexing/javascript/fix-search-javascript)."]]