【问题标题】:How to Make popup.html on specific URL如何在特定 URL 上制作 popup.html
【发布时间】:2022-07-09 19:17:35
【问题描述】:

PopUp.html 不适用于特定 URL 我想让 popup.html 在特定的 URL 上打开,例如 google.com

Manifest.json v3

{
  "name": "test",
  "version": "1.0",
  "description": "My Extension",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"],
      "js": ["popup.js"],
      "css": ["style.css"]
    }
  ],"action": { 
      "default_popup" : "Popup.html"
    }
}

我尝试使用 MV2,但它无法在 if 条件()中工作

Manifest.json v2

{
  "name": "testmv2",
  "version": "1.0",
  "description": "My Extension 2",
  "manifest_version": 2,
  "permissions": ["activeTab","tabs", "declarativeContent"],
      "background":{        
      "scripts": ["background.js"],
      "persistent": false
    },
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"],
      "js": ["popup.js"],
      "css": ["style.css"]
    }
  ],    "browser_action": { }
}

Backgound.js

document.addEventListener('DOMContentLoaded', function() {

'use strict';

chrome.tabs.getSelected(null, function(tab) {
    myFunction(tab.url);
});

function myFunction(tablink) {
var mySiteUrl = 'https://www.google.com/';

    if( tablink === mySiteUrl){
        //it's the right website
        chrome.browserAction.setPopup({popup: "Popup.html"});

    }
}
})

【问题讨论】:

  • 后台脚本在独立于选项卡中加载的任何网页的上下文中运行,因此在document 上收听DOMContentLoaded 将无效。您可以改用chrome.tabs API 通过chrome.tabs.onUpdated 收听标签更新。

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


【解决方案1】:

#mv3支持这个答案。

正如@bradcush 所说,你不能在 background.js 中使用addEventListener(更像普通的 eventListener)。为了简单起见,background.js 更像是 server.js,不能直接访问 DOM 元素。

在您的上下文中,您需要

  1. addListener chrome.tabs.onUpdated 用于更改标签
  2. 如果当前标签的 url 是你想要的,setPopup
  3. 否则 setPopup 清空。
#background.js

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {

    # Additionally, you can check for changeInfo.status

    if (/^https:\/\/www.google.com/.test(tab.url)) {  
        chrome.action.setPopup({ popup: "./popup.html"})
    } else {
        chrome.action.setPopup({ popup: "" })
    }
});

#对于mv2

您需要根据docs进行相应的更改。

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2015-07-31
    相关资源
    最近更新 更多