Mic*_*lle 10 javascript google-chrome google-chrome-extension
玩弄Chrome扩展程序.目前我已经整理了一个上下文菜单项.单击上下文菜单项时,它将itemClicked()在我的后台脚本中触发context_menu.js:
function itemClicked(info, tab) {
alert("clicked");
}
Run Code Online (Sandbox Code Playgroud)
警报触发.我也可以做像发送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);
Run Code Online (Sandbox Code Playgroud)
所以我尝试将相同的代码添加到内容脚本中:
chrome.contextMenus.onClicked.addListener(function(OnClickData info, tabs.Tab tab) {
//code to append the input here
});
Run Code Online (Sandbox Code Playgroud)
但它仍然无法奏效.我究竟做错了什么?
如何在单击后获取上下文菜单以向页面添加内容?
非常感谢!
编辑:这是我的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"]
}
Run Code Online (Sandbox Code Playgroud)
gka*_*pak 17
您可能误解了后台页面的概念(及其更年轻,更资源友好和首选的兄弟:事件页面)和内容脚本的概念.
内容脚本:
背景页面:
该chrome.contentMenus API仅适用于一个背景页.因此,您必须创建任何上下文菜单并在onClicked那里监听事件(在后台页面中).
单击上下文菜单后,可以使用Programmatic Injection将一些代码(或内容脚本)注入活动选项卡的Web页面.
下面是演示此方法的示例扩展的源代码.
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
]
}
Run Code Online (Sandbox Code Playgroud)
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 });
}
});
Run Code Online (Sandbox Code Playgroud)
(如果注入的代码足够复杂,注入.js文件可能更好.有关Programmatic Injection的更多信息.)
| 归档时间: |
|
| 查看次数: |
6346 次 |
| 最近记录: |