扩展的另一部分使用此代码发送消息后

chrome.runtime.sendMessage({greeting: "hello"});

任何可以使用此消息传递API的Rx.js专家
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
});

并将其包装在发出新消息并允许sendResponse的Observable中?

简单地将传入消息作为Observable发出非常容易。
const MessagingObservable = Rx.Observable.create(observer => {
  chrome.runtime.onMessage.addListener(listener);
  function listener(request, sender, sendResponse) {
    observer.next(request);
  }
  return () => {
    chrome.runtime.onMessage.removeListener(listener);
  };
});

但是如何绑定(bind)sendResponse回调?

最佳答案

您可以使用内置的fromEventPattern函数来创建可观察对象,如下所示:

const messages = Rx.Observable.fromEventPattern(
  handler => chrome.runtime.onMessage.addListener(handler),
  handler => chrome.runtime.onMessage.removeListener(handler),
  (request, sender, sendResponse) => ({ request, sender, sendResponse })
);

请注意,对fromEventPattern的调用包括一个结果选择器,因此,可观察对象发出的值包含requestsendersendResponse,您可以像这样使用它们:

messages.subscribe(({ request, sender, sendResponse }) => {
  console.log(request);
  sendResponse(/* ... whatever ... */);
});

为了支持异步调用sendResponse,监听器需要能够返回true。这可以通过包装handler来完成,如下所示:

const messages = Rx.Observable.fromEventPattern(
  handler => {
    const wrapper = (request, sender, sendResponse) => {
      const event = { async: false, request, sender, sendResponse };
      handler(event);
      return event.async;
    };
    chrome.runtime.onMessage.addListener(wrapper);
    return wrapper;
  },
  (handler, wrapper) => chrome.runtime.onMessage.removeListener(wrapper)
);

并且您将像这样使用它:

messages.subscribe(event => {
  console.log(event.request);
  event.async = true;
  setTimeout(() => event.sendResponse(/* ... whatever ... */), 1000);
});

关于google-chrome-extension - Rx.js,Chrome Messaging API,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51046571/

10-09 09:28