YouTube Lite (更好的体验)

使YouTube界面更加动态,隐藏包含关键词的视频,添加下载按钮并在无广告页面(嵌入youtube-nocookie)中打开视频。

目前为 2023-10-01 提交的版本。查看 最新版本

// ==UserScript==
// @name       YouTube Lite (melhor experiência)
// @name:pt       YouTube Lite (melhor experiência)
// @name:es       YouTube Lite (la mejor experiencia)
// @name:en       YouTube Lite (best experience)
// @name:fr       YouTube Lite (meilleure expérience)
// @name:ru       YouTube Lite (лучший опыт)
// @name:ja       YouTube Lite (最高のエクスペリエンス)
// @name:ko       YouTube Lite (최고의 경험)
// @name:zh-TW       YouTube Lite (更佳體驗)
// @name:zh-CN       YouTube Lite (更好的体验)

// @namespace    http://linkme.bio/jhonpergon/?userscript=youtube_lite
// @version      1.4
// @author       Jhon Pérgon

// @description       Deixa a interface do YouTube mais leve, oculta vídeos com palavras-chaves, adiciona botão de download e abre o vídeo em uma página livre de anúncios (embed youtube-nocookie).
// @description:pt       Deixa a interface do YouTube mais leve, oculta vídeos com palavras-chaves, adiciona botão de download e abre o vídeo em uma página livre de anúncios (embed youtube-nocookie).
// @description:es      Hace que la interfaz de YouTube sea más dinámica, oculta videos con palabras clave, agrega un botón de descarga y abre el video en una página sin publicidad (embed youtube-nocookie).
// @description:en      Makes the YouTube interface lighter, hides videos with keywords, adds a download button and opens the video on an ad-free page (embed youtube-nocookie).
// @description:fr      Il rend l'interface YouTube plus dynamique, masque les vidéos avec des mots-clés, ajoute un bouton de téléchargement et ouvre la vidéo sur une page sans publicité (embed youtube-nocookie).
// @description:ru      Он делает интерфейс YouTube более динамичным, скрывает видео с ключевыми словами, добавляет кнопку загрузки и открывает видео на странице без рекламы (встроить youtube-nocookie).
// @description:ja      YouTube インターフェースをより動的にし、キーワードを含むビデオを非表示にし、ダウンロード ボタンを追加して、広告なしのページ (youtube-nocookie embed) でビデオを開きます。
// @description:ko      YouTube 인터페이스를 더욱 동적으로 만들고, 키워드로 동영상을 숨기고, 다운로드 버튼을 추가하고, 광고 없는 페이지에서 동영상을 엽니다(youtube-nocookie embed).
// @description:zh-TW      使YouTube介面更加動態,隱藏包含關鍵字的影片,新增下載按鈕,並在無廣告頁面(嵌入youtube-nocookie)中開啟影片。
// @description:zh-CN      使YouTube界面更加动态,隐藏包含关键词的视频,添加下载按钮并在无广告页面(嵌入youtube-nocookie)中打开视频。

// @match           https://www.youtube.com/*
// @match           https://m.youtube.com/*
// @match           https://music.youtube.com/*
// @match           https://youtu.be/*
// @icon         https://icons.iconarchive.com/icons/designbolts/cute-social-media/256/Youtube-icon.png
// @grant        GM_addStyle
// @license      MIT

// @grant        GM_getValue
// @grant        GM_setValue

// @compatible      chrome
// @compatible      firefox
// @compatible      opera
// @compatible      edge
// @compatible      safari
// @compatible      berrybrowser
// ==/UserScript==


(function() {
    'use strict';

  GM_addStyle('@import url("https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css");');

  // Recupere o texto salvo no armazenamento local
  var palavrasSalvas = GM_getValue('keyWords', '')

  function stringParaArray(xpalavrasChave) {
    const arrayDePalavras = xpalavrasChave.split(',');
    const palavrasLimparEspacos = arrayDePalavras
      .map(palavra => palavra.trim())
      .filter(palavra => palavra !== '');
    return palavrasLimparEspacos;
  }

  const palavrasChaveString = palavrasSalvas;
  const palavrasChave = stringParaArray(palavrasChaveString);;

  console.log(palavrasChave);

  function converterParaArray() {
      // Obtém o valor da textarea
      const listaTexto = document.getElementById('listaDeTermos').value;

      // Divide o texto em termos separados por vírgulas
      const termosArray = listaTexto.split(',');

      // Remove espaços em branco em excesso em cada termo
      const termosLimpos = termosArray.map(termo => termo.trim());

      // Exibe o resultado na página
      const resultado = document.getElementById('resultado');
      resultado.textContent = JSON.stringify(termosLimpos);
  }

  // Função para verificar se uma palavra-chave está presente em um elemento
  function verificaPalavrasChave(elemento) {
    var texto = elemento.textContent.toLowerCase();
    for (var i = 0; i < palavrasChave.length; i++) {
      var palavra = palavrasChave[i].toLowerCase();
      if (texto.includes(palavra)) {
        return true;
      }
    }
    return false;
  }


function getUrl(xxx) {
  try {
    if (typeof xxx !== 'string') {
      throw new Error('Input is not a string');
    }
    const url = new URL(xxx);
    const vParam = url.searchParams.get('v');

    if (vParam) {
      return vParam;
    }
  } catch (error) {
    console.error('ERROR "v":', error);
  }
  return null;
}



  // Função para remover tags "ytd-rich-item-renderer" com base nas palavras-chave
  function removeTagsComPalavrasChave() {
    var elementos = document.querySelectorAll("ytd-rich-item-renderer");
    elementos.forEach(function (elemento) {
      if (verificaPalavrasChave(elemento)) {
        elemento.remove();
      }
    });
  }






  // CÓDIGO IMPORTADO
  const equalText1 = "Skip Ads";
  const equalText2 = "Skip Ad";

  function addNewStyle(newStyle) {
      var styleElement = document.getElementById('styles_js');
      if (!styleElement) {
          styleElement = document.createElement('style');
          styleElement.type = 'text/css';
          styleElement.id = 'styles_js';
          document.getElementsByTagName('head')[0].appendChild(styleElement);
      }
      styleElement.appendChild(document.createTextNode(newStyle));
  }
  function skipAd(){
      if(document.getElementsByClassName("ytp-ad-skip-button").length > 0){
          if(document.getElementsByClassName("ytp-ad-skip-button")[0].childNodes[0].textContent === equalText1 || document.getElementsByClassName("ytp-ad-skip-button")[0].childNodes[0].textContent === equalText2){
              document.getElementsByClassName("ytp-ad-skip-button")[0].click();
          } else {
              setTimeout(skipAd(), 1000);
          }
      }
  }

    // Função para remover todos os elementos desnecessários
    function removerTagsScript() {
        document.title = "Youtube (Lite)";

        setTimeout(function(){
          const scripts = document.querySelectorAll('script');
          scripts.forEach(function(script) {
              script.parentNode.removeChild(script);
          });
          const tagthumbnails = document.querySelectorAll('ytd-playlist-thumbnail');
          tagthumbnails.forEach(function(thumbnail) {
              thumbnail.parentNode.removeChild(thumbnail);
          });
          const tagthumbnail2s = document.querySelectorAll('ytd-moving-thumbnail-renderer');
          tagthumbnail2s.forEach(function(thumbnail2) {
              thumbnail2.parentNode.removeChild(thumbnail2);
          });
          const tagthumbnail3s = document.querySelectorAll('ytd-thumbnail-overlay-toggle-button-renderer');
          tagthumbnail3s.forEach(function(thumbnail3) {
              thumbnail3.parentNode.removeChild(thumbnail3);
          });
          const tagthumbnail4s = document.querySelectorAll('ytd-thumbnail-overlay-inline-unplayable-renderer');
          tagthumbnail3s.forEach(function(thumbnail4) {
              thumbnail4.parentNode.removeChild(thumbnail4);
          });
          const iconsets = document.querySelectorAll('iron-iconset-svg');
          iconsets.forEach(function(iconset) {
              iconset.parentNode.removeChild(iconset);
          });
          const renderers = document.querySelectorAll('ytd-rich-shelf-renderer');
          renderers.forEach(function(renderer) {
              renderer.parentNode.removeChild(renderer);
          });
          const recomendados = document.querySelectorAll('ytd-watch-next-secondary-results-renderer');
          recomendados.forEach(function(recomendado) {
              recomendado.parentNode.removeChild(recomendado);
          });
          const recomendado2s = document.querySelectorAll('ytd-statement-banner-renderer');
          recomendado2s.forEach(function(recomendado2) {
              recomendado2.parentNode.removeChild(recomendado2);
          });
          const xplayers = document.querySelectorAll('ytd-player');
          xplayers.forEach(function(player) {
              player.parentNode.removeChild(player);
          });
          const interactions = document.querySelectorAll('yt-interaction');
          interactions.forEach(function(interaction) {
              interaction.parentNode.removeChild(interaction);
          });
          const ychats = document.querySelectorAll('ytd-live-chat-frame');
          ychats.forEach(function(ychat) {
              ychat.parentNode.removeChild(ychat);
          });
          const players = document.querySelectorAll('video');
          players.forEach(function(playerx) {
              playerx.parentNode.removeChild(playerx);
          });
          const ycanvas = document.querySelectorAll('canvas');
          ycanvas.forEach(function(ycanva) {
              ycanva.parentNode.removeChild(ycanva);
          });
          const yminiplayers = document.querySelectorAll('ytd-miniplayer');
          yminiplayers.forEach(function(yminiplayer) {
              yminiplayer.parentNode.removeChild(yminiplayer);
          });
          const ypopups = document.querySelectorAll('ytd-popup-container');
          ypopups.forEach(function(ypopup) {
              ypopup.parentNode.removeChild(ypopup);
          });
          const ythirds = document.querySelectorAll('ytd-third-party-manager');
          ythirds.forEach(function(ythird) {
              ythird.parentNode.removeChild(ythird);
          });
          const yannouncers = document.querySelectorAll('iron-a11y-announcer');
          yannouncers.forEach(function(yannouncer) {
              yannouncer.parentNode.removeChild(yannouncer);
          });
          const ymediaQuerys = document.querySelectorAll('iron-media-query');
          ymediaQuerys.forEach(function(ymediaQuery) {
              ymediaQuery.parentNode.removeChild(ymediaQuery);
          });
          const ytdAds = document.querySelectorAll('ytd-ad-slot-renderer');
          ytdAds.forEach(function(ytdAd) {
              ytdAd.parentNode.removeChild(ytdAd);
          });
          const ytdAd2s = document.querySelectorAll('ytd-rich-section-renderer');
          ytdAd2s.forEach(function(ytdAd2) {
              ytdAd2.parentNode.removeChild(ytdAd2);
          });
          const ytdAd3s = document.querySelectorAll('ytd-merch-shelf-renderer');
          ytdAd3s.forEach(function(ytdAd3) {
              ytdAd3.parentNode.removeChild(ytdAd3);
          });
          const ytdAd4s = document.querySelectorAll('tp-yt-paper-dialog');
          ytdAd4s.forEach(function(ytdAd4) {
              ytdAd4.parentNode.removeChild(ytdAd4);
          });
          const ytdAd5s = document.querySelectorAll('ytd-action-companion-ad-renderer');
          ytdAd5s.forEach(function(ytdAd5) {
              ytdAd5.parentNode.removeChild(ytdAd5);
          });

          const videosAds = document.querySelectorAll('.video-ads');
          if(videosAds){
            if (videosAds.length > 0) {
            videosAds.forEach(function(videosAd) {
                videosAd.parentNode.removeChild(videosAd);
              });
            }
          }
          const previews = document.querySelectorAll('.ytp-gradient-top');
          if(previews){
            if (previews.length > 0) {
            previews.forEach(function(preview) {
                preview.style.display = 'none';
                preview.parentNode.removeChild(preview);
              });
            }
          }

          //Remover ADS Skip
          addNewStyle('.ytp-ad-overlay-slot {display:none !important;}');
          if(window.location.href.substring(0,30) == "https://www.youtube.com/watch?"){
              skipAd();
          }

        // Selecione todos os elementos do DOM
        var allElements = document.querySelectorAll('*');
        // Itere por todos os elementos e remova os manipuladores de eventos de clique
        allElements.forEach(function(element) {
            element.click = null;
            element.onclick = null;
            element.auxclick = null;
            element.dblclick = null;
            element.copy = null;
            element.change = null;
            element.keypress = null;
            element.keydown = null;
            element.mousedown = null;
            element.mouseover = null;
        });



            //Remover eventos pré-estabelecidos
            /*let cinematicsContainer = document.getElementById('cinematics-container');
            if (cinematicsContainer) {
              const clonedElement = cinematicsContainer.cloneNode(true);
              cinematicsContainer.parentNode.replaceChild(clonedElement, cinematicsContainer);
            }
            const playerRemove = document.querySelectorAll('#player');
            for (const element of playerRemove) {
                element.remove();
              };

            const xoverlays = document.querySelectorAll('.ytp-pause-overlay');
            if (xoverlays.length > 0) {
              xoverlays.forEach(function(xoverlay) {
                xoverlay.style.display = "none";
                xoverlay.parentNode.removeChild(xoverlay);
              });
            }
            const thumbnails = document.querySelectorAll('.ytd-thumbnail');
            if (thumbnails.length > 0) {
              thumbnails.forEach(function(xthumbnail) {
                xthumbnail.style.display = "none";
                xthumbnail.parentNode.removeChild(xthumbnail);
              });
            }*/
          let mediaElements = document.querySelectorAll('video, audio');
          if(mediaElements){
            mediaElements.forEach(function (media) {
              if (typeof media.play === 'function') {
                  media.play = function () {};
                }
              });
          }




          // Obtém todos os elementos pelo ID e os remove
          const alertRemoves = document.querySelectorAll('#clarify-box');
          for (const element of alertRemoves) {
              element.remove();
            };
          const elementsToRemove = document.querySelectorAll('#video-preview');
          for (const element of elementsToRemove) {
              element.remove();
            };
          /*const elementsplay = document.querySelectorAll('#player');
          for (const element of elementsplay) {
              element.remove();
            };*/
          const adsInfo = document.querySelectorAll('#ads-info-button');
          for (const element of adsInfo) {
              element.remove();
            };

          // Troca links
          const richItemRenderers = document.querySelectorAll('ytd-rich-item-renderer');

          for (const renderer of richItemRenderers) {
            const links = renderer.querySelectorAll('a');

            for (const link of links) {
              link.style.border = '1px solid transparent';

              link.addEventListener('mouseover', function() {
                link.style.border = '1px solid #9ba2ff';
                link.style.boxShadow = '2px 3px 4px #5c3299';
              });

              link.addEventListener('mouseout', function() {
                link.style.border = '1px solid transparent';
                link.style.boxShadow = '';
              });

              if (link.href.indexOf('/watch?v=') !== -1) {
                let linkID = getUrl(link.href);
                link.setAttribute('href', `https://www.youtube-nocookie.com/embed/${linkID}?rel=0&controls=2&color=white&iv_load_policy=3&showinfo=0&modestbranding=1&hl=pt-BR&autoplay=1`);
              }
            }
          }

      }, 500);
    }

    // Função para extrair o ID do vídeo da URL
    function getVideoIdFromUrl() {
        const url = window.location.href;
        const match = url.match(/[?&]v=([^&]+)/);
        if (match && match[1]) {
            return match[1];
        }
        return null;
    }

    // Função para criar o iframe personalizado
    function createCustomIframe(videoId) {
      document.body.style.backgroundColor = "#06070b";
      document.body.style.backgroundColor = "#06070b";



      setTimeout(function(){
        let mainplayer = document.getElementById('miniplayer-bar');
        let allplayer = document.getElementById('player');

        //let youtubeLite = document.querySelector('body');

        let outroBudega = document.getElementById('player-wrap');
        if(outroBudega){
          outroBudega.innerHTML = ``;
        }

        const yframes = document.querySelectorAll('iframe');
        yframes.forEach(function(yframe) {
            yframe.parentNode.removeChild(yframe);
        });
        const ytApps = document.querySelectorAll('ytd-player-microformat-renderer');
        ytApps.forEach(function(ytApp) {
            ytApp.parentNode.removeChild(ytApp);
        });
        let interfacex = document.getElementById('primary');
        let menus = document.getElementById('upload-info');

        if (mainplayer) {
            //youtubeLite.id = "tubeliteApp";

          //let mainplayer = document.getElementById('tubeliteApp');

          const hums = document.querySelectorAll('h1');
          hums.forEach(function(hum) {
            hum.parentNode.removeChild(hum);
          });

          if(localStorage.getItem('atualReload') == "false" && localStorage.getItem('trocou') == "false" && localStorage.getItem('trocardeNovo') == "true"){
              localStorage.setItem('trocou', "true");
          }
          if(localStorage.getItem('atualReload') == "false" && localStorage.getItem('trocou') == "true" && localStorage.getItem('trocardeNovo') == "true"){
              localStorage.setItem('trocardeNovo', "false");
              mainplayer.style.width = '98%';
              mainplayer.style.maxWidth = '720px';
              mainplayer.style.height = '320px';
              mainplayer.style.maxHeight = '52%';
              mainplayer.style.zIndex = '99999';

              interfacex.style.maxWidth = '720px';
              interfacex.style.height = 'auto';
              interfacex.style.maxHeight = '320px';
              interfacex.style.position = 'absolute';
              interfacex.style.marginLeft = '0px';
              interfacex.style.marginRight = '0px';
              interfacex.style.right = '50%';
              interfacex.style.left = '50%';
              interfacex.style.bottom = '0';
              interfacex.style.top = '10px';
              interfacex.style.transform = 'translate(-50%, 0%)';

            setTimeout(function(){
              mainplayer.innerHTML += `<iframe id="xplayer" src="https://www.youtube-nocookie.com/embed/${videoId}?rel=0&controls=2&color=white&iv_load_policy=3&showinfo=0&modestbranding=1&hl=pt-BR" allow="accelerometer; autoplay; gyroscope; picture-in-picture" frameborder="0" frameborder="autoplay" scrolling="no" sandbox="allow-scripts allow-same-origin" referrerpolicy="no-referrer" allowfullscreen=""></iframe>`;
              let customIframe = document.getElementById('xplayer');
              allplayer.style.height = '320px';
              allplayer.style.maxHeight = '320px';

              customIframe.style.width = '790px';
              customIframe.style.maxWidth = '95%';
              customIframe.style.height = '85%';
              customIframe.style.maxHeight = '450px';
              customIframe.style.border = 'solid 1px #413746';
              customIframe.style.borderRadius = '.6rem';
              customIframe.style.position = 'absolute';
              customIframe.style.right = '50%';
              customIframe.style.left = '50%';
              customIframe.style.transform = 'translate(-50%, 0px)';
              customIframe.style.zIndex = '999999';
              customIframe.style.backgroundImage = "url(https://i.pinimg.com/originals/cf/ce/2f/cfce2fa4cc0ccdc49cf1482c355a50b8.gif)";
              menus.innerHTML += `<div style="width: 10px; height: 18px; padding: 8px 25px; overflow: hidden; margin: 5px; background-color: #2a292b; border: 1px solid #afc2ff; border-radius: 2em;"><a style="text-decoration: none; padding: 8px 20px; margin-left: -25px; color: rgb(246, 241, 255); font-size: 1.6rem;" href="https://www.y2mate.com/pt/youtube/${videoId}" target="_blank"><i class="bi bi-download"></i></a><div>`;
            }, 500);
            localStorage.setItem('atualReload', "true");
          }else if(localStorage.getItem('atualReload') == "true"){
              //mainplayer.innerHTML = ``;
              mainplayer.style.width = '98%';
              mainplayer.style.maxWidth = '720px';
              mainplayer.style.height = '85%';
              mainplayer.style.maxHeight = '320px';

              interfacex.style.maxWidth = '720px';
              interfacex.style.height = 'auto';
              interfacex.style.maxHeight = '320px';
              interfacex.style.position = 'absolute';
              interfacex.style.marginLeft = '0px';
              interfacex.style.marginRight = '0px';
              interfacex.style.right = '50%';
              interfacex.style.left = '50%';
              interfacex.style.bottom = '0';
              interfacex.style.top = '10px';
              interfacex.style.transform = 'translate(-50%, 0%)';
            setTimeout(function(){
              mainplayer.innerHTML += `<iframe id="xplayer" src="https://www.youtube-nocookie.com/embed/${videoId}?rel=0&controls=2&color=white&iv_load_policy=3&showinfo=0&modestbranding=1&hl=pt-BR&autoplay=1" allow="accelerometer; autoplay; gyroscope; picture-in-picture" frameborder="0" frameborder="autoplay" scrolling="no" autoplay="autoplay" sandbox="allow-scripts allow-same-origin" referrerpolicy="no-referrer" allowfullscreen=""></iframe>`;
              let customIframe = document.getElementById('xplayer');
              allplayer.style.height = '320px';
              allplayer.style.maxHeight = '320px';

              customIframe.style.width = '790px';
              customIframe.style.maxWidth = '95%';
              customIframe.style.height = '85%';
              customIframe.style.maxHeight = '450px';
              customIframe.style.border = 'solid 1px #413746';
              customIframe.style.borderRadius = '.6rem';
              customIframe.style.position = 'absolute';
              customIframe.style.right = '50%';
              customIframe.style.left = '50%';
              customIframe.style.transform = 'translate(-50%, 0px)';
              customIframe.style.zIndex = '999999';
              customIframe.style.backgroundImage = "url(https://i.pinimg.com/originals/cf/ce/2f/cfce2fa4cc0ccdc49cf1482c355a50b8.gif)";
              menus.innerHTML += `<div style="width: 10px; height: 18px; padding: 8px 25px; overflow: hidden; margin: 5px; background-color: #2a292b; border: 1px solid #afc2ff; border-radius: 2em;"><a style="text-decoration: none; padding: 8px 20px; margin-left: -25px; color: rgb(246, 241, 255); font-size: 1.6rem;" href="https://www.y2mate.com/pt/youtube/${videoId}" target="_blank"><i class="bi bi-download"></i></a><div>`;
            }, 500);
            localStorage.setItem('atualReload', "true");
          }
        }else{
          alert("Note: The standard interface elements failed.")
          localStorage.setItem('atualReload', "true");
          let youtubeLite = document.querySelector('body');
          youtubeLite.id = "tubeliteApp";
          let mainplayer = document.getElementById('tubeliteApp');
          mainplayer.innerHTML = ``;
          mainplayer.style.width = '98%';
          mainplayer.style.maxWidth = '720px';
          mainplayer.style.height = '85%';
          mainplayer.style.maxHeight = '450px';
          setTimeout(function(){
            mainplayer.innerHTML = `<iframe id="xplayer" src="https://www.youtube-nocookie.com/embed/${videoId}?rel=0&controls=2&color=white&iv_load_policy=3&showinfo=0&modestbranding=1&hl=pt-BR&autoplay=1" allow="accelerometer; autoplay; gyroscope; picture-in-picture" frameborder="0" frameborder="autoplay" scrolling="no" autoplay="autoplay" sandbox="allow-scripts allow-same-origin" referrerpolicy="no-referrer" allowfullscreen=""></iframe>`;
            mainplayer.innerHTML += `<div style="width: 10px; height: 18px; padding: 8px 25px; overflow: hidden; margin: 5px; background-color: #2a292b; border: 1px solid #afc2ff; border-radius: 2em; position: absolute; top: 59%; right: 50%; left: 50%; transform: translate(-50%, 0%);"><a style="text-decoration: none; padding: 8px 20px; margin-left: -25px; color: rgb(246, 241, 255); font-size: 1.6rem;" href="https://www.y2mate.com/pt/youtube/${videoId}" target="_blank"><i class="bi bi-download"></i></a><div></p>`;
            let customIframe = document.getElementById('xplayer');
            customIframe.style.width = '98%';
            customIframe.style.maxWidth = '720px';
            customIframe.style.height = '55%';
            customIframe.style.maxHeight = '420px';
            customIframe.style.border = 'solid 1px #413746';
            customIframe.style.borderRadius = '.6rem';
            customIframe.style.position = 'absolute';
            customIframe.style.right = '50%';
            customIframe.style.left = '50%';
            customIframe.style.transform = 'translate(-50%, 5px)';
            customIframe.style.zIndex = '999999';
            customIframe.style.backgroundImage = "url(https://i.pinimg.com/originals/cf/ce/2f/cfce2fa4cc0ccdc49cf1482c355a50b8.gif)";
            menus.innerHTML += `<div style="width: 10px; height: 18px; padding: 8px 25px; overflow: hidden; margin: 5px; background-color: #2a292b; border: 1px solid #afc2ff; border-radius: 2em;"><a style="text-decoration: none; padding: 8px 20px; margin-left: -25px; color: rgb(246, 241, 255); font-size: 1.6rem;" href="https://www.y2mate.com/pt/youtube/${videoId}" target="_blank"><i class="bi bi-download"></i></a><div>`;
          }, 500);
        }
        // Altera o título da página para "Youtube Lite"
        document.title = "Youtube (Lite)";
      }, 2100);
    }



    // Função para limpar todos os cookies do site na primeira vez
    function limparCookies() {
        if(localStorage.getItem('verificarCookies') == null){
            localStorage.setItem('verificarCookies', "primeiraVez");
        }
        if (localStorage.getItem('verificarCookies') == "primeiraVez" || localStorage.getItem('verificarVersao') !== "1.4"){
          localStorage.setItem('verificarVersao', "1.4");
          alert("Note: You are accessing Youtube Lite for the first time, to ensure your correct operation let's clean the cookies and restart the page.")
          localStorage.setItem('verificarCookies', "tudoSuave");
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = cookies[i];
              var igualPos = cookie.indexOf('=');
              var nome = igualPos > -1 ? cookie.substr(0, igualPos) : cookie;
              document.cookie = nome + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
          }
          window.location.reload();
        }
    }




    var xmyMenus = document.createElement('div');
    xmyMenus.style.position = 'absolute';
    xmyMenus.style.width = '80%';
    xmyMenus.style.height = '40px';
    xmyMenus.style.top = '52px';
    xmyMenus.style.right = '2%';
    xmyMenus.style.textAlign = 'center';
    xmyMenus.style.zIndex = '999';
    xmyMenus.style.marginTop = '1px';
    xmyMenus.style.borderBottom = '1px solid #332a73';
    xmyMenus.style.backgroundColor = '#130f24a1';

    // Cria o botão "Editar Palavras"
    var editarPalavrasButton = document.createElement('button');
    editarPalavrasButton.style.fontSize = '17px';
    editarPalavrasButton.style.marginTop = '9px';
    editarPalavrasButton.style.backgroundColor = '#000';
    editarPalavrasButton.style.color = '#fff';
    editarPalavrasButton.style.borderRadius = '3px';
    editarPalavrasButton.style.height = '27px';
    editarPalavrasButton.style.padding = '2px 1.5%';
    editarPalavrasButton.innerHTML = "<i style='font-size:14px'>Abc</i> → <i class='bi bi-card-list'></i> = <i class='bi bi-trash3'></i>";


    var gaveta = document.createElement('div');
    gaveta.style.position = 'fixed';
    gaveta.style.top = '40px';
    gaveta.style.zIndex = '9999';
    gaveta.style.width = '320px';
    gaveta.style.height = '170px';
    gaveta.style.right = '50%';
    gaveta.style.left = '50%';
    gaveta.style.textAlign = 'center';
    gaveta.style.transform = 'translate(-50%, 12%)';
    gaveta.style.border = '1px solid #fff';
    gaveta.style.backgroundColor = 'rgba(14, 10, 28, 0.94)';
    gaveta.style.overflow = 'hidden';
    gaveta.style.display = 'none';


    var textarea = document.createElement('textarea');
    textarea.style.width = '200px';
    textarea.style.width = '97%';
    textarea.style.height = '130px';
    textarea.style.pla = '130px';
    textarea.style.backgroundColor = '#0d0d0f';
    textarea.style.color = '#fff';
    textarea.style.padding = '3px 4px';
    textarea.placeholder = 'Exemples: futebol, Big Brother, etc';
    textarea.value = palavrasSalvas;

    var salvarButton = document.createElement('button');
    salvarButton.style.marginTop = '2px';
    salvarButton.style.width = '97%';
    salvarButton.style.padding = '2px 10px';
    salvarButton.style.backgroundColor = '#000';
    salvarButton.style.color = '#fff';
    salvarButton.style.borderRadius = '3px';
    salvarButton.innerHTML = 'Save and hide all';

    // Adiciona os elementos criados como filhos de xmyMenus
    xmyMenus.appendChild(editarPalavrasButton);
    gaveta.appendChild(textarea);
    gaveta.appendChild(salvarButton);
    document.body.appendChild(xmyMenus);
    document.body.appendChild(gaveta);


    // Adicione um evento de clique ao botão de abrir a gaveta
    editarPalavrasButton.addEventListener('click', function() {
        gaveta.style.display = 'block';
    });

    // Adicione um evento de clique ao botão de salvar
    salvarButton.addEventListener('click', function() {
        var palavrasSalvas = textarea.value;
        GM_setValue('keyWords', palavrasSalvas);
        alert('Saved! The page will reload to activate hiding the new keywords.');
        gaveta.style.display = 'none';
        window.location.reload();
    });


      const youtubeTag = document.querySelector('ytd-app');
      if (youtubeTag) {
        youtubeTag.setAttribute('id', 'ytdLite');
        youtubeTag.style.marginTop = '40px';
        //document.getElementById("guide").innerHTML += myMenus;
      }



    // Função para verificar a URL a cada 2 segundos
    function checkURL() {
        limparCookies();
        removerTagsScript();
        removeTagsComPalavrasChave();

        const currentURL = window.location.href;
        if (currentURL !== localStorage.getItem('lastCheckedURL') && currentURL.includes("/watch?v=")) {
            xmyMenus.style.display = 'none';
            youtubeTag.style.marginTop = '0px';
            window.location.reload();
            localStorage.setItem('lastCheckedURL', currentURL);
            localStorage.setItem('trocou', "false");
            localStorage.setItem('trocardeNovo', "true");
            localStorage.setItem('atualReload', "false");
            const videoId = getVideoIdFromUrl();
            if (videoId) {
                createCustomIframe(videoId);
            }
        }
    }

    // Inicia o loop para verificar a URL a cada 1 segundos
    setInterval(checkURL, 550);

    // Verifica a URL quando o script é carregado pela primeira vez
    const videoId = getVideoIdFromUrl();
    if (videoId) {
        xmyMenus.style.display = 'none';
        youtubeTag.style.marginTop = '0px';
        createCustomIframe(videoId);
    }

})();