Communication from an injected script to the content script with a response

蓝咒 提交于 2019-12-19 09:09:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!