2015-05-13 93 views
2

我已經從內容腳本中插入了iframe。它工作正常。但是,如果我想在iframe上顯示父級的HTML內容,我必須使用消息傳遞來在iframe和內容腳本之間進行通信,但它不起作用。然後,我嘗試將消息從iframe發送到「活動頁面」,然後再發送到「內容腳本」。一旦內容腳本收到消息,它將查詢html內容並回復。它也不起作用。我怎樣才能使它工作?Chrome擴展將消息從iFrame發送到事件頁面,然後發送到內容腳本

內容腳本:

var iframe = document.createElement('iframe'); 
iframe.id = "popup"; 
iframe.src = chrome.runtime.getURL('frame.html'); 
document.body.appendChild(iframe); 

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
    if (msg.from === 'event' && msg.method == 'ping') { 
    sendResponse({ data: 'pong' }); 
    } 
}); 

活動頁面:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
    if (msg.from === 'popup' && msg.method === 'ping') { 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     chrome.tabs.sendMessage(tabs[0].id, { 
     from: 'event', 
     method:'ping'}, function(response) { 
      sendResponse(response.data); 
     }); 
    }); 
    } 
}); 

frame.js

// This callback function is never called, so no response is returned. 
// But I can see message's sent successfully to event page from logs. 
chrome.runtime.sendMessage({from: 'popup', method:'ping'}, 
    function(response) { 
    $timeout(function(){ 
    $scope.welcomeMsg = response; 
    }, 0); 
}); 

回答

2

我發現了一個RELAT編輯問題。 https://stackoverflow.com/a/20077854/772481

從chrome.runtime.onMessage.addListener的文檔:

此功能失效時,事件偵聽器返回時,除非你從事件​​監聽器返回true,指示要異步發送一個響應(這個將保持消息通道開放到另一端,直到sendResponse被調用)。

所以我必須返回true來表示sendResponse是異步的。

活動頁面:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
    if (msg.from === 'popup' && msg.method === 'ping') { 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
     chrome.tabs.sendMessage(tabs[0].id, { 
     from: 'event', 
     method:'ping'}, function(response) { 
      sendResponse(response.data); 
     }); 
    }); 
    return true; // <-- Indicate that sendResponse will be async 
    } 
}); 
相關問題