2016-11-25 68 views
0

我正在查看嵌入了iframe的網頁。我需要從網頁和所有嵌入式iframe的擴展瀏覽器操作中收集信息。我有以下代碼:如何從iframe中的內容腳本傳遞消息?

清單

{ 
    "manifest_version": 2, 
    ... 
    "content_scripts": [ 
    { 
     "all_frames": true, 
     "js": [ "contentscript.js" ], 
     "matches": [ "http://*/*", "https://*/*", "file:///*" ], 
     "run_at": "document_start" 
    } 
    ], 
    ... 
} 

瀏覽器操作彈出

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { 
    chrome.tabs.sendMessage(tabs[0].id,{command: 'collectPageDetails'},function (details) { 
     console.log('got details'); 
    }); 
}); 

內容腳本

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { 
    if (msg.command === 'collectPageDetails') { 
     console.log('getting page details'); 
     sendResponse({ details: 'something' }); 
     return true; 
    } 
}); 

我在這裏看到的行爲是該消息被接收主頁面和iframe。我可以通過在頁面控制檯中看到兩個getting page details實例來驗證此情況。

但是,我只收到一個迴應瀏覽器操作的響應(got details僅在瀏覽器操作中記錄了一次),這似乎只來自主頁而不是嵌入式iframe。

如何通過消息傳遞從頁面中嵌入的iframe進行通信?我期待在我的瀏覽器動作function (details) { }中發生兩次回調。

回答

1

chrome.runtime.onMessagesendRespnse()功能可用於至多一次發送單個響應於消息。這並不意味着它可以每幀使用一次,但總共可以使用一次。當描述sendResponse功能,Chrome documentation說[重點煤礦]:

函數調用(最多一次)當你有一個響應。參數應該是任何可以用JSON的對象。 如果在同一文檔中有多個onMessage偵聽器,則只有一個可能發送響應。

因此,您需要使用其他方法將消息發送到後臺腳本。這通常是chrome.runtime.sendMessage()(內容腳本)與後臺腳本中的chrome.runtime.onMessage偵聽器配對。您需要爲消息定義一些格式,以定義背景腳本的消息內容。例如,你可以這樣做:

內容腳本:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { 
    if(msg.command === 'collectPageDetails') { 
     console.log('getting page details'); 
     chrome.runtime.sendMessage({type:'collectPageDetailsResponse',details:'something'}); 
    } 
}); 

背景腳本:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
    if(msg && msg.type === 'collectPageDetailsResponse') { 
     //Received a details response. 
     let tabId = sender.tab.id; 
     let frameId = sender.tab.frameId; 
     console.log('got details:', msg.details, ' From tabId:',tabId, ' frameId:',frameId); 
    } 
}); 
+0

消息是要走的路。謝謝。 – kspearrin

相關問題