【发布时间】:2019-04-23 21:17:25
【问题描述】:
我正在尝试编写我的第一个浏览器扩展程序,但我似乎无法通过单击上下文菜单项来触发单击处理程序。 console.log 调用似乎没有向控制台吐出任何东西,我尝试使用 alert() 以防万一“背景”脚本(不确定背景和内容脚本之间的区别究竟是什么),但是似乎也没有做任何事情。
当我在测试页面的输入中选择一些文本时,右键单击并选择加密或解密,没有任何反应;不在控制台或开发人员工具的网络选项卡中。我做错了什么?
manefest.json:
{
"manifest_version": 2,
"name": "my name",
"description": "my description",
"version": "1.0",
"background": {
"scripts": ["jquery-3.2.1.min.js", "background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"]
}
],
"permissions": [
"activeTab",
"contextMenus",
"http://my.hostname.com/"
]
}
background.js:
/**
* A handler which will run the analysis of the DOM element's selected text
*/
function clickHandler(info, tab) {
"use strict";
console.log(info);
console.log(tab);
// get selected text as encrypt/decrypt
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, "get selection", null, function(selection) {
var data = {
"action": action,
"selection": selection
};
var max_length = 4095;
if (data.selection.length > max_length) {
data.selection = data.selection.substring(0, max_length);
}
var url = "http://my.hostname.com/";
jQuery.post(url, data, function (response) {
chrome.tabs.sendMessage(tabs[0].id, response);
}, "json");
});
});
}
/**
* Create a context menu items to allow encode/decode
*/
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
"id": "encrypt",
"title": "Encrypt",
"type": "normal",
"contexts": ["editable"]
});
chrome.contextMenus.create({
"id": "decrypt",
"title": "Decrypt",
"type": "normal",
"contexts": ["selection"]
});
chrome.contextMenus.onClicked.addListener(clickHandler);
});
【问题讨论】: