我正在编写一个简单的Chrome扩展程序,可启用已禁用的下拉菜单。
如果我在控制台中运行相同的脚本,它可以完美地运行。但是,通过扩展,它调用函数但不执行任何操作。
提前感谢您的帮助。
的manifest.json
{
"name": "4x6 Mac Menu",
"manifest_version": 2
"version": "0.1.4",
"description": "Overrides Disabled Drop Down",
"permissions": ["contextMenus"],
"background": {
"scripts": ["sample-click.js"]
}
}
样品click.js
function Enable46(info, tab) {
console.log("Enable 4x6 was clicked.");
var inputs = document.getElementsByClassName('psSelect');
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
console.log("Drop Enabled.");
}
chrome.contextMenus.create({
title: "Enable 4x6",
contexts: ["page"],
onclick: Enable46,
});
我还尝试了另一种方法让一个监听器作为背景,当我得到控制台日志时,该事件实际上并没有执行该功能
的manifest.json
{
"name": "4x6 Enable",
"description": "Enable 4x6 Print Option on Mac",
"version": "0.1",
"manifest_version": 2,
"permissions": [
"contextMenus",
"activeTab"
],
"background": {
"persistent": false,
"scripts": ["bg.js"]
}
}
bg.js
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "4x6 Label",
contexts: ["all"]
});
/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
/* Create the code to be injected */
var code = [
'var input = document.getElementsByClassName("psSelect");',
'for(var i = 0; i < inputs.length; i++) { inputs[i].disabled = false; }'
].join("\n");
console.log("Enable 4x6 was clicked.");
/* Inject the code into the current tab */
chrome.tabs.executeScript(tab.id, { code: code });
}
});
答案 0 :(得分:0)
此解决方案有效。无论出于何种原因,它必须分成3个文件。
<强>的manifest.json 强>
{
"name": "Enable Dropdown",
"description": "Enable Dropdown Menu",
"version": "0.3",
"manifest_version": 2,
"permissions": [
"contextMenus",
"activeTab"
],
"background": {
"persistent": false,
"scripts": ["bg.js"]
}
}
<强> bg.js 强>
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "Enable Dropdown",
contexts: ["all"]
});
/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
/* Inject the code into the current tab */
/* chrome.tabs.executeScript(tab.id, { code: code }); */
chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
}
});
<强> content_script.js 强>
var inputs = document.getElementsByClassName('psSelect');
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
document.getElementById("PrintLabelsPrinter").value = "1-1";