Para agregar código JavaScript personalizado o contenido HTML antes de la etiqueta <body> en cada página de tu portal, haz lo siguiente:
Selecciona Publicar > Portales y selecciona tu portal.
Haga clic en Configuración en la página de destino.
También puedes seleccionar Configuración en el menú desplegable de la barra de navegación superior.
Haz clic en la pestaña Secuencias de comandos personalizadas.
En la sección Secuencias de comandos personalizadas, ingresa el código JavaScript personalizado en el cuadro de texto. Puedes incluir varias secuencias de comandos. **
Haz clic en Guardar.
En las siguientes secciones, se proporcionan ejemplos de secuencias de comandos personalizadas:
Ejecuta una secuencia de comandos personalizada durante un evento onLoad o onUnload JavaScript.
Define secuencias de comandos personalizadas para que se ejecuten cuando cada página de tu portal:
Se carga en el DOM mediante el evento de JavaScript onLoad.
Se aleja del uso del evento de JavaScript onUnload.
Tu función personalizada debe definirse como parte de portal.pageEventListeners en el espacio de nombres global (declarado en la variable window).
Los eventos onLoad y onUnload reciben como sus primeros parámetros la ruta actual de la página (/quickstart, por ejemplo). La función onUnload recibe como su segundo parámetro el valor que muestra la llamada onLoad y permite que el contexto pase entre los dos eventos. Usa onUnload para limpiar los objetos de escucha de eventos que ya no son necesarios y realiza otras actividades de limpieza.
Por ejemplo:
<script>
window.portal={};window.portal.pageEventListeners={onLoad:(path)=>{if(path==='/quickstart'){//Changetextcontentoffirst<p>elementtosomething//else.(DOMmustbeloadedwhenonLoadiscalled)document.getElementsByTagName('p')[0].textContent='Welcome to the quick start! Be sure to send us your feedback.';//printacustommessagetotheconsoleeverysecondwhileuserison//quickstartpage.constinterval=window.setInterval(()=>console.log('Hello'),1000);returninterval;}returnundefined;},onUnload:(path,contextReturnedFromOnLoad)=>{if(contextReturnedFromOnLoad!=null){//Stopprintingcustommessagetoconsoleeverysecond.window.clearInterval(contextReturnedFromOnLoad)}},};
</script>
Agrega una ventana emergente de consentimiento para el uso de cookies
Se pueden usar secuencias de comandos personalizadas para implementar una solución de consentimiento de cookies. Existen varias opciones populares de código abierto implementadas en JavaScript. Selecciona uno que satisfaga sus requisitos de cumplimiento específicos.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-03 (UTC)"],[[["\u003cp\u003eThis content provides guidance on adding custom JavaScript code to Apigee and Apigee hybrid portals for enhancing functionalities like integrating third-party tools or implementing cookie consent popups.\u003c/p\u003e\n"],["\u003cp\u003eCustom scripts can be added through the portal settings under the "Custom Scripts" tab, requiring proper enclosure within \u003ccode\u003e<script>\u003c/code\u003e tags to prevent display and security issues.\u003c/p\u003e\n"],["\u003cp\u003eScripts can be executed during page load (onLoad) or when navigating away from a page (onUnload) by defining functions within \u003ccode\u003eportal.pageEventListeners\u003c/code\u003e in the global namespace, allowing for dynamic content modification and cleanup activities.\u003c/p\u003e\n"],["\u003cp\u003eAvoid manipulating the DOM with custom scripts in order to prevent overriding or changing the built-in behaviors of the portal, however it can be used to integrate third-party services.\u003c/p\u003e\n"],["\u003cp\u003eExamples are given for executing custom scripts during JavaScript events and adding a cookie consent popup by using open source solutions like the Cookie Info Script.\u003c/p\u003e\n"]]],[],null,["# Adding custom scripts\n\n*This page\napplies to **Apigee** and **Apigee hybrid**.*\n\n\n*View [Apigee Edge](https://docs.apigee.com/api-platform/get-started/what-apigee-edge) documentation.*\n\n\u003cbr /\u003e\n\n| **Warning**: Custom scripts are supported for integrating third-party services such as web metrics or feedback tools. Avoid using custom scripts to manipulate the DOM to override or otherwise change built-in behaviors of the portal.\n\nTo add custom JavaScript code or HTML content before the `\u003cbody\u003e` tag on each\npage in your portal: \n\n### Cloud Console UI\n\n1. In the Apigee in Cloud console, go to the **Distribution \\\u003e Portals** page.\n\n [Go to Portals](https://console.cloud.google.com/apigee/portals)\n2. Click **Settings** in the navigation menu.\n\n3. In the **Custom Scripts** section, enter the custom JavaScript code in the\n text box. You can include multiple scripts.\n\n | **Warning** : Make sure to enclose your custom code in `\u003cscript\u003e` and `\u003c/script\u003e` tags. Invalid JavaScript code has the potential to impact the correct display of content or introduce security vulnerabilities across your entire site.\n\n \u003cbr /\u003e\n\n4. Click **Save**.\n\n### Classic UI\n\n1. Select **Publish \\\u003e Portals** and select your portal.\n2. Click **Settings** on the landing page. Alternatively, you can select **Settings** in the drop-down in the top navigation bar.\n3. Click the **Custom Scripts** tab.\n4. In the **Custom Scripts** section, enter the custom JavaScript code in the text box. You can include multiple scripts. **Warning** : Make sure to enclose your custom code in `\u003cscript\u003e` and `\u003c/script\u003e` tags. Invalid JavaScript code has the potential to impact the correct display of content or introduce security vulnerabilities across your entire site.\n5. Click **Save**.\n\nThe following sections provide examples of custom scripts:\n\n- [Executing a custom script during and onLoad or onUnload JavaScript event](#javascript-event)\n\n- [Adding a cookie consent popup](#cookie-consent)\n\nSee also [Configuring analytics tracking](/apigee/docs/api-platform/publish/portal/api-portal-analytics).\n\nExecuting a custom script during an onLoad or onUnload JavaScript event\n-----------------------------------------------------------------------\n\nDefine custom scripts to be executed when each page in your portal:\n\n- Loads into the DOM using the `onLoad` JavaScript event.\n- Is navigated away from using the `onUnload` JavaScript event.\n\nYour custom function must be defined as part of the `portal.pageEventListeners` in the global namespace (declared on the `window` variable).\n\nBoth the `onLoad` and `onUnload` events receive as their first parameters the current path of the page (`/quickstart`, for example). The `onUnload` function receives as its second parameter the return value from the `onLoad` call enabling context to be passed between the two events. Use `onUnload` to clean up the event listeners that are no longer required and perform other clean up activities.\n\nFor example: \n\n \u003cscript\u003e\n window.portal = {};\n window.portal.pageEventListeners = {\n onLoad: (path) =\u003e {\n if (path === '/quickstart') {\n // Change text content of first \u003cp\u003e element to something\n // else. (DOM must be loaded when onLoad is called)\n document.getElementsByTagName('p')[0].textContent =\n 'Welcome to the quick start! Be sure to send us your feedback.';\n // print a custom message to the console every second while user is on\n // quickstart page.\n const interval =\n window.setInterval(() =\u003e console.log('Hello'), 1000);\n return interval;\n }\n return undefined;\n },\n onUnload: (path, contextReturnedFromOnLoad) =\u003e {\n if (contextReturnedFromOnLoad != null) {\n // Stop printing custom message to console every second.\n window.clearInterval(contextReturnedFromOnLoad)\n\n }\n },\n };\n \u003c/script\u003e\n\nAdding a cookie consent popup\n-----------------------------\n\nCustom scripts may be used to implement a cookie consent solution. There are a number of popular open source options implemented in\nJavaScript; select one that meets your specific compliance requirements.\n\nFor example, the following script uses the [Cookie Info Script](https://cookieinfoscript.com/). \n\n \u003cscript type=\"text/javascript\" id=\"cookieinfo\" src=\"//cookieinfoscript.com/js/cookieinfo.min.js\"\u003e\n \u003c/script\u003e"]]