【问题标题】:How to change Text based on specific URLs in Chrome Extension?如何根据 Chrome 扩展中的特定 URL 更改文本?
【发布时间】:2020-06-06 21:21:26
【问题描述】:

我第一次尝试开发 chrome 扩展程序,但我遇到了一些困难。 我想要达到的目标: 每次重新加载新 URL 时,它都会检查它是否是我定义的特定 URL 之一,比如说 - 如果重新加载 URL = https://www.google.com/,将文本更改为“这是 google”。 如果重新加载 URL = https://translate.google.com/,将文本更改为“这是 google transalte”,等等 20 个 URL。 当没有重新加载任何 URL 时,它将停留在最后一个状态。

如有任何帮助,将不胜感激。

Popup.html

<!DOCTYPE html>
<html>
<head>

    <style>
    </style>

</head>

<link rel="stylesheet" type="text/css" href="art.css"> <!--Include art.css File-->

<body>
    <button id="click"></button>

    <h1>H1</h1> 
    <h2>The Text I want to change</h2>
    <div class="square"></div> 
    <h3>by X</h3>

</body>
</html>

background.js

chrome.runtime.onInstalled.addListener(function () {



    chrome.tabs.insertCSS(tabId, {
        file: "art.css"
    });


});

manifest.json

{
  "name": "X2",
  "version": "1.0",
  "description": "X3",
  "permissions": [ "tabs", "activeTab", "declarativeContent", "storage" ], 
  "background": {
    "scripts": [  "background.js" ], //Background Scripts
    "persistent": false
  },

  "web_accessible_resources": [ 
    "art.css" 
  ],

  "page_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"
    }
  },

  "icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
  },

  "manifest_version": 2
}

【问题讨论】:

    标签: javascript html css google-chrome google-chrome-extension


    【解决方案1】:
    1. 从 manifest.json 和 background.js 文件中删除 background 部分。
    2. 从 manifest.json 中删除 web_accessible_resources 部分
    3. 从 manifest.json 中的 permissions 中删除 declarativeContenttabsstorage
    4. 在 manifest.json 中将 page_action 替换为 browser_action
    5. 创建 popup.js 并在 popup.html 的末尾加载它:

        <script src=popup.js></script>
      </body>
      
    6. popup.js 将在每次显示弹出窗口时运行,这是整个文件:

      chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        const url = tabs[0].url;
        const host = new URL(url).hostname;
        const text =
          host === 'www.google.com' && 'This is google' ||
          host === 'www.google.com' && 'This is google translate';
        if (text) {
          document.querySelector('h2').textContent = text;
        }
      });
      

    弹出窗口是一个单独的页面,因此要对其进行调试,您应该使用它自己的开发工具,可以通过在弹出窗口内右键单击打开,然后单击上下文菜单中的“检查”。

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 2023-03-26
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多