2014-10-30 204 views
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。

+0

你正在混合一个背景页面和当前页面。脚本sample.js和background.js运行在不同的上下文中。请阅读https://developer.chrome.com/extensions/overview#arch – Xan 2014-10-30 15:23:33

+0

Chrome扩展API目前不提供任何方式来了解在激活上下文菜单之前哪个DOM元素已被点击。 (尽管我想在找出通信节点的最佳方式之后在某些时候将此功能添加到Chromium中,因为背景页面与内容脚本/页面完全不同,正如@Xan所说的。contextMenus.onClicked事件是在后台页面中触发,而点击的节点仅在内容脚本/页面中可用)。 – 2014-10-30 23:44:23

+0

那么当事件被触发时,有没有其他方法可以获取DOM元素?我无法用contextualMenu做任何事情? – 2014-10-31 09:26:29

回答

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"}); 
    }); 

这是从官方文档。 当我尝试这一点,我已经得到了这个错误:错误事件处理程序(未知):无法读取未定义 堆栈跟踪的特性“送别”:类型错误:无法读取的不确定

财产“告别”我不知道这个简单的例子有什么问题。这就像我从我的contentscript.js没有答案