Chrome扩展:单击选项卡中的事件

Chrome extension: Click event in tab?

本文关键字:事件 选项 扩展 单击 Chrome      更新时间:2023-09-26

Hej,

我在Chrome API上搜索了一整天,但找不到答案。Quick:是否可以在选项卡上添加一个图标并附加一个点击侦听器?或者通常是选项卡上的点击监听器?

谢谢!

是的,使用chrome.tabs.executeScript api是可能的。或带有content_scripts:

injectedScript.js

document.getElementById('btn1').addEventListener('click',function () {
    alert('button click!');
});

manifest.json

"content_scripts": [
    {
      "matches": ["http://www.example.com/webPage.html"],
      "js": ["injectedScript.js"]
    }
],

网页.html

<button id="btn1">clickMe!</button>

有关更多信息,请参阅程序注射

编辑:

您不能将事件添加到选项卡本身,我认为最好的方法是使用上下文菜单。这个例子是丑陋的代码,但这使工作。。。(我对我的英语感到抱歉(。

manifest.json

 "background":{"scripts":["background.js"]},
  "permissions": ["contextMenus", "tabs","activeTab","<all_urls>"]

background.json

function apdateTabList() {
    chrome.contextMenus.removeAll(function() {
        chrome.tabs.query({url:'*://*/*'}, function (tabs) {
            var currTab;
            for (var i=0; currTab = tabs[i];i++) {
                chrome.contextMenus.create({
                    id : currTab.id.toString(),
                    title: currTab.title || currTab.url,
                    contexts:['all'],
                    onclick : function(info) {
                        chrome.tabs.executeScript(Number(info.menuItemId), {code:'alert("injected")'});
                    }
                });
            }
        });
    });
}
apdateTabList();
chrome.tabs.onCreated.addListener(apdateTabList);
chrome.tabs.onUpdated.addListener(apdateTabList);
chrome.tabs.onMoved.addListener(apdateTabList);
chrome.tabs.onDetached.addListener(apdateTabList);
chrome.tabs.onAttached.addListener(apdateTabList);
chrome.tabs.onRemoved.addListener(apdateTabList);
chrome.tabs.onReplaced.addListener(apdateTabList);

不,在选项卡本身上没有可以创建的UI。

点击选项卡不是你能捕捉到的事情——你能得到的唯一事件是更改活动选项卡,你不能真正说出这是如何发生的,也不能阻止它——在你收到事件时,它已经发生了。