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