Auto Close Panel & Enable Grounding/Context in Google AI Studio

Automatically enables "Grounding with Google Search" and "Browse the URL context" and closes the Run settings panel after the aistudio page loads.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

Necesitarás instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Necesitará instalar una extensión como Tampermonkey para instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name        Auto Close Panel & Enable Grounding/Context in Google AI Studio
// @namespace   Violentmonkey Scripts
// @match       https://aistudio.google.com/*
// @run-at      document-start
// @version     1.0
// @author      Bui Quoc Dung
// @description Automatically enables "Grounding with Google Search" and "Browse the URL context" and closes the Run settings panel after the aistudio page loads.
// @license     MIT
// @grant       none
// ==/UserScript==

(function () {
  'use strict';

  const DELAY_MS_CLOSE_PANEL = 1000;
  const RETRY_TIMES_CLOSE_PANEL = 2;
  const SELECTOR_CLOSE_BUTTON = 'button[aria-label="Close run settings panel"]';
  let lastHandledUrlForPanel = null;
    const SELECTORS_ENABLE_BUTTONS = [
    'button[aria-label="Grounding with Google Search"]',
    'button[aria-label="Browse the url context"]'
  ];
  let lastHandledUrlForEnable = null;
  function closeSettingsPanelWithRetries() {
    if (lastHandledUrlForPanel === location.href) return;
    lastHandledUrlForPanel = location.href;

    for (let i = 0; i < RETRY_TIMES_CLOSE_PANEL; i++) {
      setTimeout(() => {
        try {
          const button = document.querySelector(SELECTOR_CLOSE_BUTTON);
          if (button) {
            button.click();
          }
        } catch (e) {
          console.error('Error trying to close settings panel:', e);
        }
      }, DELAY_MS_CLOSE_PANEL * (i + 1));
    }
  }

  function waitForElement(selector, timeout = 1000) {
    return new Promise((resolve, reject) => {
      const interval = 100;
      let elapsed = 0;
      const timer = setInterval(() => {
        const el = document.querySelector(selector);
        if (el) {
          clearInterval(timer);
          resolve(el);
        } else if ((elapsed += interval) >= timeout) {
          clearInterval(timer);
          reject(new Error(`Element not found for selector: ${selector}`));
        }
      }, interval);
    });
  }

  async function enableSwitches() {
      if (lastHandledUrlForEnable === location.href) return;
      lastHandledUrlForEnable = location.href;

    for (const selector of SELECTORS_ENABLE_BUTTONS) {
      try {
        const button = await waitForElement(selector, 2000);
        if (button.getAttribute('aria-checked') === 'false') {
          button.click();
        }
      } catch (err) {
      }
    }
  }

  function runAllTasks() {
      setTimeout(() => {
        enableSwitches();
        closeSettingsPanelWithRetries();
      }, 1000);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', runAllTasks);
  } else {
    runAllTasks();
  }

  (function patchHistory() {
    const _push = history.pushState;
    const _replace = history.replaceState;

    history.pushState = function (...args) {
      const res = _push.apply(this, args);
      window.dispatchEvent(new Event('locationchange'));
      return res;
    };

    history.replaceState = function (...args) {
      const res = _replace.apply(this, args);
      window.dispatchEvent(new Event('locationchange'));
      return res;
    };

    window.addEventListener('popstate', () =>
      window.dispatchEvent(new Event('locationchange'))
    );
    window.addEventListener('locationchange', runAllTasks);
  })();
})();