2017-04-20 167 views
0

我知道有可能將postMessage從網頁擴展到Chrome擴展,並獲得良好的迴應回到網頁,但它可能是另一種方式嗎?從Chrome擴展到網頁的通信

我的問題「我需要能夠發送的請求到一個網頁,等待我可以在擴展使用。也許不是使用於PostMessage的迴應?」

我知道文檔說「只有網頁可以啓動連接」。 (https://developer.chrome.com/extensions/messaging#external-webpage

這裏是我想嘗試如此的票價。

background.js

chrome.extension.sendMessage("Hello from extension to webpage"); 
window.postMessage("Hello from extension to webpage"); 
chrome.tabs.sendMessage(TAB_ID, "Hello from extension to webpage"); 

webpage.js(而不是擴展的一部分)

window.onmessage = (event) => { 
    // Waiting for that message. 
    console.info("Event received ", event); 
} 
window.chrome.runtime.connect(CHROME_EXTENSION_APP_ID).onMessage.addListener(function(){ 
    function(request, sender, sendResponse) { 
    console.info("Event received from the extension", event); 
    } 
}) 

任何想法可以理解 :)

+0

使用內容腳本和常規DOM消息,如CustomEvent。 – wOxxOm

+0

嘗試檢查[與嵌入頁面通信](https://developer.chrome.com/extensions/content_scripts#host-page-communication)和相關的SO [post](http://stackoverflow.com/a/ 19048254/5995040),如前所述,如果您正在使用內容腳本,則可能會發生這種情況。您也可以查看[論壇](https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/lTUDJYClBF0),其中介紹瞭如何將信息從擴展程序傳遞到網頁。希望這可以幫助。 –

回答

1

您可以使用chrome.tabs.executeScript API來做到這一點。

 var dataToWebPage = {text: 'test', foo: 1, bar: false}; 
     chrome.tabs.executeScript({ 
      code: '(' + function(params) { 
       //This function will work in webpage 
       console.log(params); //logs in webpage console 
       return {success: true, response: "This is from webpage."}; 
      } + ')(' + JSON.stringify(dataToWebPage) + ');' 
     }, function(results) { 
      //This is the callback response from webpage 
      console.log(results[0]); //logs in extension console 
     }); 

請注意,它需要標籤permission

+0

謝謝Mûhámmàd - executeScript工程.. – Nederby