当我从ChromeExtension点击contextualMenu中的某个活动时,我想与当前页面的DOM进行互动。
有我的代码:
的manifest.json
{
"name": "jQuery DOM",
"version": "1",
"permissions":[
"http://*/",
"contextMenus"
],
"description": "Manipulate the DOM when the page is done loading",
"background": {
"scripts": ["sample.js", "jquery.min.js"]},
"browser_action": {
"name": "Manipulate DOM",
"icons": ["icon.png"],
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
"manifest_version": 2
}
sample.js
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A generic onclick callback function.
function editOnClick(info, tab) {
alert($("body").html());
}
// Create a parent item and two children.
var parent = chrome.contextMenus.create({"title": "Therefore"});
var child1 = chrome.contextMenus.create(
{"title": "Éditer", "parentId": parent, "onclick": editOnClick});
当我尝试这个时,我会收到警报框:
<script src="sample.js"></script>
<script src="jquery.min.js"></script>
但是在 background.js 中使用$("body").append('TEST')
,我可以直接与当前页面的DOM进行交互。
我不知道为什么我不能从上下文菜单。
答案 0 :(得分:0)
我得到了一些答案。我不得不创建一个由content-script.js触发的事件,因为它无法从后台访问DOM页面。
我的新代码例如:
<强> background.js 强>
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
<强> contentscript.js 强>
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
来自官方文档。 当我尝试这个时,我得到了这个错误:事件处理程序中的错误(未知):无法读取属性&#39;告别&#39;未定义的 堆栈跟踪:TypeError:无法读取属性&#39;告别&#39;未定义的
我不知道这个简单例子的错误。这就像我的contentscript.js没有回答