2013-01-05 56 views
3

當從後臺腳本獲取消息時,出現問題。我的頭腦幾乎被吹了,哪裏錯了?試圖從後臺腳本獲取消息

清單

{ 
    "name":"Some name", 
    "version":"0.1", 
    "manifest_version": 2, 
    "description":"extension for Google Chrome", 
    "permissions": ["tabs","http://*/*", "https://*/*", "<all_urls>","notifications","contextMenus","alarms","tabs","bookmarks"], 
    "content_scripts":[ 
    { 
     "matches":["<all_urls>"], 
     "css":["style.css"], 
     "js":["content.js","jquery.js"] 
    } 
    ], 
    "background": { 
     "scripts": ["background.js","jquery.js"], 
     "persistent": false 
    }, 
    "icons":{ 
     "16": "images/icon16.png", 
     "48": "images/icon48.png", 
     "128": "images/icon128.png" 
    }, 
    "browser_action": { 
     "default_icon": { 
      "19": "images/icon19.png",   
      "38": "images/icon38.png" 
     }, 
     "default_title": "Order Checker", 
     "default_popup": "popup.html" 
    } 
} 

background.js

chrome.tabs.getSelected(null, function(tab) { 
    console.log('Loaded!'); 
    chrome.tabs.sendMessage(tab.id, { 
     greeting: "hello" 
    }); 
    console.log('Sended on '+tab.id+'...'); 
}); 

content.js

chrome.extension.onMessage.addListener(function(msg, _, request) { 
    console.log('Getting request...'); 
    console.log(msg.greeting); 
}); 

在背景頁面我收到控制檯2消息,正如預期的那樣。但是在內容頁面上我沒有任何消息,所以我認爲這是content.js中的代碼問題。我做錯了什麼?

回答

1

chrome.tabs.getSelected()已從Chrome 16中棄用,請改爲使用chrome.tabs.query()

Problem in Your Script

chrome.tabs.getSelected()返回當前所選的選項卡的參考,其擴展後的負載chrome://chrome/extensions/所以你的背景頁正在發送消息到擴展頁面,內容腳本do not execute

修改您的後臺腳本以適應chrome.tabs.query(),您可以在網頁控制檯中看到消息!

參考