我面临一个问题。通过消息传递,我将 DOM 数据从内容脚本传输到后台页面。我想知道的是如何在选项页面和后台页面之间建立通信通道。应用程序编程接口chrome.extension.getBackgroundPage()
没有用。传统的消息传递也不是通过sendRequest
and addlistener
在职的 。如何将此数据从后台页面传输到选项页面?有人可以提供一个经过测试的片段来解释吗?
这就是我一直在尝试的。
在我的 contentscript.js 中
<script>
var selected_Text ="";
window.addEventListener("dblclick",function(event){
selected_Text = String(window.getSelection());
chrome.extension.sendRequest({greeting: "maprender",name:selected_Text}, function(response) {
alert("reached here")
console.log(response.farewell);
});
//i am to then load options.html on DOM like this
var Div = document.createElement("iframe");
Div.setAttribute('src', chrome.extension.getURL('options.html'));
Div.setAttribute("style","width:130px;height:80px;position:absolute;left:10px;");
Div.setAttribute("id","xyz");
document.body.appendChild(Div);
</script>
我像这样检索选定的文本作为 background.html
<script>
var Addr_details={
place:null
};
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "maprender")
{
alert("reached here sendin resp"+request.name);
Addr_details.place = request.name;
sendResponse({farewell: "goodbye"});
}
else
sendResponse({}); // snub them.
});
</script>
现在要在选项页面 options.html 访问此文本的值,我尝试了 2 种方法
一种是像这样使用 chrome.extension.getBackgroundPage() :
<script>
function init(){
var bkg = chrome.extension.getBackgroundPage();
alert("the selected text is "+bkg.Addr_details.place);
}
</script>
init 是 options.html 的 onload 。这没有给我值。事实上它只是在 chrome.extension.backgroundPage 初始化时终止。
我尝试的另一种方法是从 contentscript.js 创建一个类似的请求(就像 contentscript.js 中已经存在的请求),并使用不同的问候语,并在 options.html 中添加一个侦听器。这似乎在接收方也不起作用(选项页面)因为我在请求后在内容脚本中收到回调。我肯定做错了什么,不是吗?请帮忙。