2016-08-15 77 views
1

我在嘗試構建Chrome擴展,但無法從彈出窗口向內容腳本發送消息。請告訴我問題在哪裏。Chrome中的彈出窗口和內容腳本之間的通信

彈出腳本代碼:

  $(document).ready(function(){ 
      $('#button').click(function(){ 
       chrome.tabs.query({active: true, currentWindow: true},function(tabs) { 
        chrome.tabs.sendMessage(tabs[0].id, {message: "hello"}); 
     }); 
    }); 
}); 

內容腳本代碼:

chrome.extension.onMessage.addListener(
function(request, sender) { 
    alert("Contentscript has received a message from from background script: '" + request.message + "'"); 
    }); 

這是manifest.json的:

{ 
    "manifest_version" : 2, 
    "name" : "First My Chrome Extension", 
    "version" : "0.0.1", 
    "description" : "The first web-app using chrome extension technology", 
    "icons" : { 
    "16" : "images/icon16px.png", 
    "48" : "images/icon48px.png", 
    "128" : "images/icon128px.png" 
    }, 


"background": { 
    "scripts": ["scripts/background.js"] 

    }, 



    "browser_action" :{ 
    "default_icon":{ 
     "48" : "images/icon48px.png" 
    }, 
    "default_title" : "Nghoangvutn", 
    "default_popup" : "popup.html" 
    }, 
    "content_scripts":[ 
    { 
    "matches":[ 
     "<all_urls>" 
     ], 
    "js" : [ 
     "scripts/jquery.js", 
     "scripts/content.js" 
     ] 

    } 
    ], 

    "permissions" : [ 
    "tabs", 
    "storage" 
    ] 

} 
+0

彈出窗口和網頁控制檯中的任何錯誤信息? –

+0

沒有錯誤信息。它只是不工作。也許消息傳遞失敗。我不知道問題在哪裏 –

+0

檢查這些鏈接:http://stackoverflow.com/questions/13646389/send-message-from-popup-to-content-script和http://stackoverflow.com/questions/6108906/chrome-extension-message-passing-from-popup-content-script – abielita

回答

0

內容腳本代碼應當更新使用以下方法chrome.runtime.onMessage.addListener。請注意從chrome.extensionchrome.runtime的更改。

chrome.runtime.onMessage.addListener(
function(request, sender) { 
    alert("Contentscript has received a message from from background script: '" + request.message + "'"); 
}); 
+0

我遵循你的幫助,但沒有任何變化,內容腳本不起作用。 –

+0

你是否正確加載內容腳本? – 10100111001

+0

它應該使用清單文件動態地或靜態地添加到頁面。 – 10100111001

相關問題