2016-05-13 57 views
0

我有一个铬扩展我正在努力。我的background.js脚本会执行一些操作,并返回一个字符串(backgroundResponse)回到我的content_script.js。Chrome扩展程序 - 将数据从content_script.js传递回网页?

网页(index.html的):如下所示这工作得很好

jQuery("#clickmenow").on("click", function (event) 
{ 
    document.dispatchEvent(new CustomEvent('funcDoRequest', { 
     'detail': { task: 'dir' } 
    })); 

    // I want backgroundResponse here instead somehow..? 
}); 
<a href="#" id="clickmenow">Click me now</a> 

background.js

document.addEventListener("funcDoRequest", function (stuff) 
{ 
    chrome.runtime.sendMessage(stuff.detail, function (backgroundResponse) 
    { alert('Returning data from background.js: ' + backgroundResponse); }); 
}); 

我的问题是,我想响应backgroundResponse将同步返回到以某种方式点击jQuery。所以当有人点击#clickmenow时,它最终会运行我的background.js文件,并且一直返回onclick(或dispatchEvent),而不仅仅是content_script.js,这就是它现在正在做的事情。我怎样才能做到这一点?我无法弄清楚。

+0

那应该是你的_content.js_ – Xan

回答

0

我想响应backgroundResponse要返回同步

这不会是可能的 - 与背景页面的任何通信将涉及异步消息传递。


基于事件的通信不能用明确的答复,但你可以一样好trigger another event的页面听。您可以包含某种内容脚本必须复制到响应以区分事件的唯一ID。


最后,如果这是你在你事先知道一个域控制下的网页,可以考虑使用externally_connectable并直接说话的背景页。

-1

两个内容脚本和后台页面可以使用chrome.runtime.sendMessage API沟通

//content script 
jQuery("#clickmenow").on("click", function (event) { 
    chrome.runtime.sendMessage({'detail': { task: 'dir' }}, function (backgroundResponse) { alert('Returning data from background.js: ' + 
     // handle backgroundResponse 
    }); 

}); 


//background page 

    chrome.runtime.onMessage.addListener(function(detailFromContentScript, sender, sendResponse) { 
    // handle detailFromContentscript 
    var backgroundResponse = process(detailFromContentScript) 

    // then send back response to content script 
    sendResponse(backgroundResponse) 
}) 
相关问题