Use el complemento de Chrome para inyectar scripts js en la página

razón

Cuando mi computadora está conectada al auricular, el sonido externo no se apaga automáticamente y la realtek高清晰音频管理器configuración interna sigue siendo inútil. Entonces pensé que probablemente se debía a las frecuentes actualizaciones de win10 recientemente, y la versión del administrador era incorrecta, así que fui al sitio web oficial de realtek para descargar la última versión. De, entonces. . . Hice clic en el gobotón y no respondí. Eché un vistazo al habitual f12 y encontré que la consola reportaba un error con
Inserte la descripción de la imagen aquí
jQuery. Luego miré a la red y descubrí que la forma de introducir jquery por cdn no se cargaba. https://code.jquery.com/jquery-1.12.4.min.js
Inserte la descripción de la imagen aquí
Solo hay una verdad, y la introducción de jQuery falló, fui a Baidu Aprendí cómo inyectar scripts externos en el sitio web y descubrí que se puede lograr con la tecnología de complemento de Chrome. Luego fui al sitio web oficial de Chrome y verifiqué el documento . Si no quieres leer en inglés, puedes ir al documento de complemento del navegador de velocidad 360.

Comenzando con el complemento de Chrome

Inserte la descripción de la imagen aquí
Importar complemento
Inserte la descripción de la imagen aquí

Descarga lograda

Inserte la descripción de la imagen aquí

Código de muestra

manifest.json

{
    
    
  "name": "插件demo",
  "version": "1.0",
  "description": "入门学习用",
    "permissions": ["activeTab","declarativeContent","storage"],
    "background": {
    
    
        "scripts": ["background.js"],
        "persistent": false
      },
    "browser_action": {
    
    
      "default_popup": "popup.html",
       "default_icon": {
    
    
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
      }
    },
      "content_scripts": [
    {
    
    "js":["content_scripts.js"],"matches":["<all_urls>"]}
  ],
      "icons": {
    
    
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    },
    "options_page": "options.html",
   
  "manifest_version": 2
}

content_scripts.js

const theScript = document.createElement('script');
theScript.src = 'https://cdn.bootcss.com/jquery/3.2.1/jquery.js';
document.body.appendChild(theScript);

console.log('查看脚本是否注入成功')

background.js

'use strict';

chrome.runtime.onInstalled.addListener(function() {
    
    
  chrome.storage.sync.set({
    
    color: 'pink'}, function() {
    
    
    console.log("color,pink");
  });
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    
    
      chrome.declarativeContent.onPageChanged.addRules([{
    
    
        conditions: [new chrome.declarativeContent.PageStateMatcher({
    
    
          pageUrl: {
    
    hostEquals: 'developer.chrome.com'},
        })
        ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
      }]);
    });
});

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
      <style>
        .box{
     
     
          width: 200px;
          height: 400px;
        }
        button {
     
     
          height: 30px;
          width: 30px;
          outline: none;
        }
      </style>
    </head>
    <body>
      <div class="box">
        <h3>点击可以改变背景色和文字颜色</h3>
      <button id="changeColor"></button>
        
      </div>
        <script src="popup.js"></script>
    </body>

</html>

popup.js

'use strict';

let changeColor = document.getElementById('changeColor');
chrome.storage.sync.get('color', function(data) {
    
    
  changeColor.style.backgroundColor = data.color;
  changeColor.setAttribute('value', data.color);
});

 changeColor.onclick = function(element) {
    
    
    let color = element.target.value;
    chrome.tabs.query({
    
    active: true, currentWindow: true}, function(tabs) {
    
    
      chrome.tabs.executeScript(
          tabs[0].id,
          {
    
    code: 'document.body.style.backgroundColor = "' + color + '";'});
    });
  };

options.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
      <style>
        .box{
     
     
          width: 200px;
          height: 400px;
        }
        button {
     
     
          height: 30px;
          width: 30px;
          outline: none;
        }
      </style>
    </head>
    <body>
      <div class="box">
        <h3>点击可以改变背景色和文字颜色</h3>
      <button id="changeColor"></button>
        
      </div>
        <script src="popup.js"></script>
    </body>

</html>

options.js

// 'use strict';

// const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1'];

// function constructOptions(kButtonColors) {
    
    
//   for (let item of kButtonColors) {
    
    
//     let button = document.createElement('button');
//     button.style.backgroundColor = item;
//     button.addEventListener('click', function() {
    
    
//       chrome.storage.sync.set({color: item}, function() {
    
    
//         console.log('color is ' + item);
//       })
//     });
//     page.appendChild(button);
//   }
// }
// constructOptions(kButtonColors);

Supongo que te gusta

Origin blog.csdn.net/weixin_35958891/article/details/107712677
Recomendado
Clasificación