通过响应从注入脚本传递到内容脚本 [英] Communication from an injected script to the content script with a response
问题描述
遵循这个问题,注入脚本和内容脚本之间的通信可以这样进行:
//内容脚本
window.addEventListener(getChromeData,函数(数据){
//做Chrome事物;
},false);
//注入脚本
window.dispatchEvent(new CustomEvent(getChromeData,{data:'whatever'}));
我想知道是否有办法将返回的数据用于注入脚本,一个承诺还是一个回调机制?
您可以使用一次性侦听器来实现基于承诺的响应。
我会传递一个额外的请求ID,以便一次性侦听器不会意外获取困惑;
内容脚本:
window.addEventListener (getChromeData,function(evt){
var request = evt.detail;
var response = {requestId:request.id};
//使用request.data执行Chrome操作,添加东西到response.data
window.dispatchEvent(new CustomEvent(sendChromeData,{detail:response}));
},false);
注入脚本:
var ChromeRequest =(function(){
var requestId = 0;
function getData(data){
var id = requestId ++;
return new Promise(function(resolve,reject){
var listener = function(evt){
if(evt.detail.requestId == id){
//注销self
window.removeEventListener(sendChromeData,listener);
resolve(evt.detail.data);
}
}
window.addEventListener (sendChromeData,listener);
var payload = {data:data,id:id};
window.dispatchEvent(new CustomEvent(getChromeData,{detail :payload)));
});
}
return {getData:getData};
})();
ChromeRequest.getData(whatever)。then(function(data){/ * ... * /});
请注意,您必须使用 detail
CustomEvent
的属性,它不是一个任意的属性。
Following this question, communicating between an injected script and content script can be made that way:
// Content script
window.addEventListener("getChromeData", function(data) {
// do Chrome things;
}, false);
// Injected script
window.dispatchEvent(new CustomEvent("getChromeData", {data: 'whatever'}));
I wanted to know if there is a way to make use of returned data into the injected script, using a promise or a callback mechanism?
The communication back is again done with an event. You can use a one-shot listener to achieve a promise-based response.
I will be passing an extra request ID so that one-shot listeners don't accidentally get confused; maybe it's an overkill.
Content script:
window.addEventListener("getChromeData", function(evt) {
var request = evt.detail;
var response = {requestId: request.id};
// do Chrome things with request.data, add stuff to response.data
window.dispatchEvent(new CustomEvent("sendChromeData", {detail: response}));
}, false);
Injected script:
var ChromeRequest = (function(){
var requestId = 0;
function getData(data) {
var id = requestId++;
return new Promise(function(resolve, reject) {
var listener = function(evt) {
if(evt.detail.requestId == id) {
// Deregister self
window.removeEventListener("sendChromeData", listener);
resolve(evt.detail.data);
}
}
window.addEventListener("sendChromeData", listener);
var payload = { data: data, id: id };
window.dispatchEvent(new CustomEvent("getChromeData", {detail: payload}));
});
}
return { getData: getData };
})();
ChromeRequest.getData("whatever").then(function(data){/* ... */});
Please note, you have to use detail
attribute of a CustomEvent
, it's not an arbitrary property.
这篇关于通过响应从注入脚本传递到内容脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!