2016-05-13 248 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) 
})