2014-10-30 201 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沒有答案