尝试构建Chrome扩展程序。目前,我已经整理了一个上下文菜单项。单击上下文菜单项后,它将itemClicked()
在我的背景脚本中触发context_menu.js
:
function itemClicked(info, tab) {
alert("clicked");
}
警报触发。我也可以做一些事情,例如通过发送ajax请求itemClicked()
但是,我不能将任何元素附加到页面上(或任何形式的DOM操作)。甚至像这样基本的东西都行不通:
var d = document.createElement('div');
d.setAttribute("css", "width: 100px; height: 100px; background-color: red; position: fixed; top: 70px; left: 30px; z-index: 99999999999;");
document.body.appendChild(d);
因此,我尝试将相同的代码添加到内容脚本中:
chrome.contextMenus.onClicked.addListener(function(OnClickData info, tabs.Tab tab) {
//code to append the input here
});
但这仍然行不通。我究竟做错了什么?
单击后如何获取上下文菜单以将某些内容添加到页面?
非常感谢!
编辑:这是我的manifest.json(删除了不相关的名称/描述等内容)
{
"permissions": [
"activeTab",
"tabs",
"cookies",
"contextMenus"
],
"background": {
"scripts": ["context_menu.js"]
},
"browser_action": {
"default_icon": "icon16.png",
"default_css": "popup.css",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["vendor/jquery-1.8.2.min.js", "config.js", "content_script.js"]
}
],
"web_accessible_resources": ["popup.html"]
}
您可能误解了背景页面(及其更年轻,更资源友好且更可取的同级对象:事件页面)和内容脚本的概念。
内容脚本:
背景页面:
该chrome.contentMenus API仅适用于一个背景页。因此,您必须创建任何上下文菜单并在其中侦听onClicked
事件(在后台页面中)。
单击上下文菜单后,您可以使用Programmatic Injection将一些代码(或内容脚本)注入活动选项卡的网页。
下面是演示此方法的示例扩展的源代码。
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false, // <-- let's make it an event page
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"activeTab" // <-- here, sufficient for our purpose
]
}
background.js:
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "Click me",
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 d = document.createElement("div");',
'd.setAttribute("style", "'
+ 'background-color: red; '
+ 'width: 100px; '
+ 'height: 100px; '
+ 'position: fixed; '
+ 'top: 70px; '
+ 'left: 30px; '
+ 'z-index: 9999; '
+ '");',
'document.body.appendChild(d);'
].join("\n");
/* Inject the code into the current tab */
chrome.tabs.executeScript(tab.id, { code: code });
}
});
(如果注入的代码足够复杂,则注入.js文件可能是一个更好的主意。有关Programmatic Injection的更多信息。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句