Javascript Chrome扩展-将数据从content_script.js传递回网页?

Javascript Chrome扩展-将数据从content_script.js传递回网页?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在做一个chrome扩展。我的background.js脚本执行了一些操作,并将字符串(backgroundResponse)返回给我的content\u script.js。如图所示,这项工作正常: 网页(index.html): 我的问题是,我希望响应backgroundResponse在单击时同步返回到调用jQuery。因此,当有人单击#clickmenow时,它会运行mybackground.js的东西,并将值返回到onclick(或dispatchEvent),而不仅仅是conte

我正在做一个chrome扩展。我的background.js脚本执行了一些操作,并将字符串(backgroundResponse)返回给我的content\u script.js。如图所示,这项工作正常:

网页(index.html):

我的问题是,我希望响应backgroundResponse在单击时同步返回到调用jQuery。因此,当有人单击#clickmenow时,它会运行mybackground.js的东西,并将值返回到onclick(或dispatchEvent),而不仅仅是content_script.js,这正是它现在所做的。我该怎么做?我想不出来

我希望响应backgroundResponse同步返回

这是不可能的-任何与后台页面的通信都将涉及异步消息传递


基于事件的通信不能使用显式响应,但您也可以使用页面侦听的响应。您可以包含某种唯一ID,内容脚本必须将其复制到响应中,以区分事件



最后,如果你是在你事先知道的一个域上控制网页,考虑直接使用和对后台页面进行对话。

< P>内容脚本和后台页面都可以使用ChrimeRunTime.sDeMeMeAPI 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)
})
那应该是你的content.js
document.addEventListener("funcDoRequest", function (stuff)
{
    chrome.runtime.sendMessage(stuff.detail, function (backgroundResponse)
    { alert('Returning data from background.js: ' + backgroundResponse); });
});
//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)
})