0
当我点击ChromeExtension的contextualMenu中的事件时,我想与当前页面的DOM交互。Chrome扩展程序:DOM + ContextualMenu
有我的代码:
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>
但$("body").append('TEST')
在我的background.js,我可以直接与我当前页面的DOM进行交互。 我不知道为什么我不能从contextualMenu。
你正在混合一个背景页面和当前页面。脚本sample.js和background.js运行在不同的上下文中。请阅读https://developer.chrome.com/extensions/overview#arch – Xan 2014-10-30 15:23:33
Chrome扩展API目前不提供任何方式来了解在激活上下文菜单之前哪个DOM元素已被点击。 (尽管我想在找出通信节点的最佳方式之后在某些时候将此功能添加到Chromium中,因为背景页面与内容脚本/页面完全不同,正如@Xan所说的。contextMenus.onClicked事件是在后台页面中触发,而点击的节点仅在内容脚本/页面中可用)。 – 2014-10-30 23:44:23
那么当事件被触发时,有没有其他方法可以获取DOM元素?我无法用contextualMenu做任何事情? – 2014-10-31 09:26:29