如果您只是想從擴展到內容腳本的任何端口打開的例子,這是我能想到的最簡單的。背景只是打開一個端口併發送「Hello標籤!」通過端口,內容腳本每次點擊網頁時都會向後臺發送消息。
我覺得這很簡單,所以我不知道你爲什麼如此強調。只要確保內容選項卡在後臺嘗試連接時已經在監聽(我等待直到「完成」事件)。
的manifest.json:
{
"name": "TestExt",
"version": "0.1",
"background_page": "background.html",
"content_scripts": [{
"matches": ["http://localhost/*"], // same as background.html regexp
"js": ["injected.js"]
}],
"permissions": [
"tabs" // ability to inject js and listen to onUpdated
]
}
background.html:
<script>
var interestingTabs = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// same as manifest.json wildcard
if (changeInfo.url && /http:\/\/localhost(:\d+)?\/(.|$)/.test(changeInfo.url)) {
interestingTabs[tabId] = true;
}
if (changeInfo.status === 'complete' && interestingTabs[tabId]) {
delete interestingTabs[tabId];
console.log('Trying to connect to tab ' + tabId);
var port = chrome.tabs.connect(tabId);
port.onMessage.addListener(function(m) {
console.log('received message from tab ' + tabId + ':');
console.log(m);
});
port.postMessage('Hello tab!');
}
});
</script>
injection.js:
chrome.extension.onConnect.addListener(function(port) {
console.log('Connected to content script!');
port.onMessage.addListener(function(m) {
console.log('Received message:');
console.log(m);
});
document.documentElement.addEventListener('click', function(e) {
port.postMessage('User clicked on a ' + e.target.tagName);
}, true);
});
請發佈您迄今爲止的代碼以及清單。 – serg 2011-02-08 18:45:57