2015-05-13 65 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 
    } 
}); 
相关问题