2013-04-05 32 views
0

感謝您的閱讀。Chrome擴展彈出 - 從background.js功能設置DIV文本

我被困在我的background.js和popup.html之間傳遞信息!

在這個例子中,我想從popup.html的background.js中調用testRequest。我已經看了幾十個如何做到這一點的例子和編碼爲許多解決方案,但我沒有成功...這是我試過的解決方案之一:

Popup.html:

<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title></title> 
</head> 
<body> 
    <script type="text/javascript" src="background.js">     
      $(document).ready(function() { 
       document.getElementById("test").textContent = chrome.extension.getBackgroundPage.testRequest(); 
      }); 
    </script> 
    <div id="test"></div> 
</body> 
</html> 

background.js

var testRequest = function(){ 
return 'yay!'; 
} 

非常感謝您的幫助!

〜Brian

回答

3

你可以使用簡單的消息傳遞來做到這一點。例如:

Popup.html

<html lang="en"> 
    <head> 
    <meta charset="utf-8" /> 
    <title></title> 
    <script src="jquery.min.js"></script> 
    <script src="popup.js"></script> 
    </head> 
    <body> 
    <div id="test"></div> 
    </body> 
</html> 

popup.js

$(function() { 
    chrome.runtime.sendMessage({method:"testRequest"},function(reply){ 
    $('#test').text(reply); 
    }); 
}); 

background.js

chrome.runtime.onMessage.addListener(function(message,sender,sendRepsonse){ 
    if(message.method == "testRequest") 
    sendResponse(testRequest()); 
}); 
function testRequest(){ 
    return "yay!"; 
} 

內嵌代碼在popup.html中是不允許的,所以我們把它全部移到一個外部文件中,你已經在使用jQuery了,所以不要害怕使用它,如果你使用它,不要忘記包含它。

+0

謝謝BeardFist!我會投這個答案,但我沒有必要的REP ... :-( – Shevus 2013-04-08 16:10:40