2013-08-04 32 views
5

我已阅读文档,但仍无法使其工作。来自background.js的内容脚本中的Chrome调用函数

这里是我的清单:

{ 
    "name":"app", 
    "version":"0.1", 
    "manifest_version":2, 
    "description":"app", 
    "background":{ 
     "scripts":[ 
      "scripts/modernizr.min.js", 
      "scripts/background.js" 
      ], 
     "persistent": false 
    }, 
    "content_scripts": [ 
     { 
     "matches": ["https://*/*", "http://*/*"], 
     "js": ["scripts/content.js"], 
     "run_at": "document_end" 
     } 
    ], 
    "permissions":[ 
     "contextMenus", 
     "tabs", 
     "http://*/*", 
     "https://*/*" 
     ], 
    "icons":{ 
     "16":"images/icon_16.png", 
     "128":"images/icon_128.png" 
    } 
} 

我有content.js称为 “myFunc的” 功能。在background.js中,我有一个函数,“myHandler”由contextMenus.onClicked侦听器调用。我想从myHandler调用myFunc。我尝试使用tabs.executeScript和tabs.query,但我似乎无法获得被调用的函数。任何人都可以向我解释我应该如何让background.js在content.js中调用一个函数?

回答

9

要从背景页面调用内容脚本中的函数,首先需要知道标签ID。 contextMenus.onClicked事件有一个包含该ID的tab参数。然后使用message passing来做到这一点。

例如,在你的后台页面:

chrome.contextMenus.onClicked.addListener(function(info, tab) { 
    if (tab) 
    chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) { 
     // ... 
    }); 
}); 

在您的内容脚本:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    sendResponse(myFunc(request.args)); 
}); 
+2

要添加这个API是在过去2年发生变化,这就是它的外观,现在。 – vittore

+0

@vittore啊,这可能可以解释为什么我试图不工作。 – Lebowski156

相关问题