如何通过Chrome扩展程序检测按钮事件

how to detect the button event by chrome extension

本文关键字:检测 按钮 事件 程序 扩展 何通过 Chrome      更新时间:2023-09-26

我想检测页面中的按钮事件,我从后台注入我的脚本.js强文本文件.html,当按钮被点击时,我想提醒一些消息而不是让按钮做他的工作。所以我有两个问题,

1.我尝试在我的 srcript 中使用 jquery.js但它似乎不起作用,我在后台包含 jquery 文件.html,如何在.js文件中使用 jquery

2.点击时如何检测按钮事件?

下面是我的代码:

背景.html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
  chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null,{file:'script.js',allFrames:true});
  });
</script>

脚本.js

if( self.frameElement && self.frameElement.tagName == "IFRAME" ){
  $(":button").bind("click",function(){
    alert("iframe button");
  });
}
else{
  $(":button").bind("click",function(){
    alert("parent button");
  });
}

至于为什么脚本中的jQuery不起作用,那是因为你在background page中包含jQuery,你需要将其加载到用户页面的扩展世界中。说清楚。您的script.js应该加载到用户页面中。Chrome 将加载到该页面中,但isolated world该页面是您的扩展程序的世界。您必须像script.js一样在该页面上加载jQuery。如下:

<script>
    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.executeScript(null,{file:'jQuery.js',allFrames:true});
        chrome.tabs.executeScript(null,{file:'script.js',allFrames:true});
    });
</script>

至于你关于听按钮点击的另一个问题,从你的问题中不清楚你说的是哪个按钮。是浏览器操作按钮吗?如果是这种情况,您的代码将正常工作。如果它是用户 DOM 上的按钮,则必须如上所述添加侦听单击事件并通知您的扩展 (background.html) 的脚本,您的background页面将依次加载脚本。