javascript - 每次单击扩展按钮时无法发出响应

标签 javascript jquery google-chrome google-chrome-extension

所以我只是想在每次单击扩展按钮时获得响应。就像 AdBlock 一样,这是如何发生的

enter image description here

但相反,我只是尝试在每次单击按钮时执行 console.log() ,而没有任何可见的弹出窗口。

到目前为止我已经尝试过了

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        switch (request.directive) {
        case "popup-click":
            // execute the content script
            chrome.tabs.executeScript(null, { // defaults to the current tab
                file: "real.js", // script to inject into page and run in sandbox
                allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
            });
            sendResponse({}); // sending back empty response to sender
            break;
        default:
            // helps debug when request directive doesn't match
            alert("Unmatched request of '" + request + "' from script to background.js from " + sender);
        }
    }
);

然后是我的real.js

console.log("Yo");

但遗憾的是,当它启动时我只得到一个 Yo 。有任何想法吗?

最佳答案

如果您没有弹出窗口(单击按钮时没有任何显示),则单击按钮时将触发一个事件:

chrome.browserAction.onClicked

Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.

使用:

// In your background script
chrome.browserAction.onClicked.addListener( function() {
  // Do stuff
});

但是,如果您确实有弹出窗口,那么,正如文档提到的,此事件将不会触发。那么你的代码更合适:你只需要从弹出窗口发送一条消息,并在打开它时在后台脚本中捕获它。请参阅 this answer 中的完整示例.

关于javascript - 每次单击扩展按钮时无法发出响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335950/

相关文章:

javascript - 其他模块中的 Node 事件发射器

javascript - 更新从 Controller 发送到 View 的数据

javascript - Chrome 扩展 - 检测 URL 并执行应用程序

jquery - 当视口(viewport)很窄时,强制面包屑元素不会中断到另一行

javascript - 使用滑动脚本在 Windows 上的 Chrome 中滚动错误

javascript - 相对于视口(viewport),Intersection Observer 是否从跨域 iframe 内部工作?

javascript - Grunt Node 和 Express 本地开发 HTTPS 证书

javascript - Ipad - 我的 Webview/UIkit safari 浏览器无法运行 javascript

Jquery.validate 缺失 : after property id

javascript - 优化 colorbox 并添加额外的 jquery