首页 > 解决方案 > Chrome 扩展显示上下文菜单,左键单击而不弹出

问题描述

刚开始学习如何编写 Chrome 扩展程序。我的目标是在单击工具栏图标时从后台 js 写入控制台。

从我读过的教程中我的理解是,当没有指定弹出窗口时,图标会像一个按钮一样,当它被左键单击时,会调用 onClicked 回调。相反,实际发生的是左键单击显示默认上下文菜单。永远不会调用回调 - 可能是因为这个原因。

我确信我错过了一些非常基本的东西;如果有人能指出这一点,那将非常有帮助。作为记录,我在 Mac 上使用 Chrome 版本 80.0.3987.163。

谢谢大家。

显现:

{
    "name": "Test",
    "version": "1.0",
    "description": "",

    "manifest_version": 2,

    "permissions": ["declarativeContent"],

    "page_action": {
        "default_icon": {
          "16": "images/get_started16.png",
          "32": "images/get_started32.png",
          "48": "images/get_started48.png",
          "128": "images/get_started128.png"
        }
    },

    "icons": {
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
    },

    "content_scripts": [
        {
          "matches": ["*://*.reddit.com/r/*"],
          "js": ["content.js"]
        }
      ],

    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
}

内容.js:

console.log("Content script running...");

背景.js:

console.log("Background script running...");

const iconRules = [{
    conditions: [
        new chrome.declarativeContent.PageStateMatcher({
            pageUrl: {hostEquals: 'reddit.com'},
        })
    ],
    actions: [new chrome.declarativeContent.ShowPageAction()]
}];

chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules(iconRules);
});

chrome.pageAction.onClicked.addListener(function(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        console.log("Clicked!")
    })
});

访问reddit时:

显示突出显示的图标。

左键单击图标时:

显示默认上下文菜单。

标签: google-chromegoogle-chrome-extension

解决方案


经过更多的实验,我终于弄清楚了为什么这不起作用:pageURL 不匹配。

实际主机是 www.reddit.com。将 hostEquals 更改为 hostSuffix 会阻止 Chrome 显示上下文菜单;onClicked 回调被调用。

我不知道为什么当条件不匹配时 Chrome 甚至会激活图标。


推荐阅读