【问题标题】:How to trigger a function on specific websites from a chrome extension?如何从 chrome 扩展程序触发特定网站上的功能?
【发布时间】:2016-05-08 20:52:05
【问题描述】:

最近开始使用 Chrome 扩展程序。 我试图弄清楚如何仅在特定网站上执行功能。

例如,我只想在 Stack Overflow 上显示一个警告框。我正在使用 Chrome 的声明性内容 API 来匹配主机。

我无法在 SO 上找到类似的问题。

我的 manifest.json 文件正在后台运行以下代码块。

'use strict';

chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
        conditions: [
            new chrome.declarativeContent.PageStateMatcher({
                pageUrl: {
                    hostEquals: 'stackoverflow.com'
                }
            })
        ],
        actions: [new chrome.declarativeContent.SOOnlyFunction()]
    }]);
});
});

function SOOnlyFunction()
{
    alert('On SO');
}

【问题讨论】:

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


    【解决方案1】:

    您不能将chrome.declarativeContent 用于除已作为操作内置的内容之外的任何内容。

    目前具体是ShowPageActionSetIconRequestContentScript(仍处于试验阶段)。

    之所以不能轻易扩展,是因为declarativeContent 是在本机代码中实现的,作为 JavaScript 事件处理程序的更有效替代方案。

    总的来说,将其归结为 Chrome 开发人员提出的一个雄心勃勃但基本上不可行/欠发达/放弃的想法,类似于 declarativeWebRequest 的命运。


    请参阅the other answer 了解使用上述 JS 处理程序的实现思路。

    或者,您仍然可以使用内容脚本declared in the manifest 将其设为“声明性”,该脚本只会在预定义的域上激活(只要您事先知道该域是一个常量)。然后他们可以自己做某事或poke the event/background page 做某事。

    最后,如果您的目标是重定向/阻止请求,webRequest API 是值得关注的。

    【讨论】:

    • 天哪!最后一行突然让我感觉不太好。你会建议我选择 Chrome 标签吗?不过,我听说它会阻塞我的 RAM。但同样,过早的优化是万恶之源。
    • 对于您所描述的,最好的办法是在清单中声明一个内容脚本,并从那里触发您的逻辑(如果您需要后台页面做某事,可能使用消息传递)。与尝试收听 tabs.onUpdated 相比,它产生的噪音要少得多,并且需要更少的权限(您需要可怕的 "tabs" 才能读取 URL)
    • 太棒了。我会继续的。
    【解决方案2】:

    您可以使用 Chrome API 来实现此行为:

    1. 当一个新的页面被加载时,你可以调用

      chrome.tabs.onUpdated

      这里可以过滤url

    2. 以及创建通知。

      chrome.notifications.create

    在您的清单中添加这些对象:

    "permissions": [  "activeTab","tabs","notifications" ],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
    

    这是我的 background.js 的样子。

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
      if(changeInfo.url != null){
    
         console.log("onUpdated." + " url is "+changeInfo.url);
         // creates Notification.
        showNotification();
    
      }
    
    });
    
    function showNotification() {
    
        chrome.notifications.create( {
          iconUrl: chrome.runtime.getURL('img/logo128.png'),
          title: 'Removal required',
          type: 'basic',
          message: 'URL is',
          buttons: [{ title: 'Learn More' }],
          isClickable: true,
          priority: 2,
        }, function() {});
    
    }
    

    它不完整,但你会得到这个想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多