google-chrome - 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时:
左键单击图标时:
解决方案
经过更多的实验,我终于弄清楚了为什么这不起作用:pageURL 不匹配。
实际主机是 www.reddit.com。将 hostEquals 更改为 hostSuffix 会阻止 Chrome 显示上下文菜单;onClicked 回调被调用。
我不知道为什么当条件不匹配时 Chrome 甚至会激活图标。
推荐阅读
- jenkins - 需要来自 Jenkins 的正确外观的电子邮件通知:包括自上次构建以来所做的 SVN 更改以及构建期间的错误(如果有)
- vbscript - VBS 快速循环线路
- python - 两点云之间的 3D 插值
- ruby-on-rails - 是否可以保留在 CircleCI 上运行的测试生成的 VCR 磁带
- delphi - 将 SysUtils.WrapText() 与包含单引号的字符串一起使用
- c# - GZipStream -- 解压后的文件缺少数据
- google-apps-script - 首次执行后多次触发脚本
- sql - 将多行转换为具有特定列名的列
- java - 将文本文件附加到文本区域
- php - 如何在codeigniter中使用imagemagick裁剪图像?