chrome 扩展 - 我如何等待 chrome.runtime 函数?

2024-03-07

我在后台的操作是访问该站点并从那里获取信息,问题是代码在收到信息之前继续运行。 附上显示问题的代码:

背景.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
fetch(request.input, request.init).then(function(response) {
    return response.text().then(function(text) {
        sendResponse([{
            body: text,
            status: response.status,
            statusText: response.statusText,
        }, null]);
    });
}, function(error) {
    sendResponse([null, error]);
    });
    return true;
});

actions.js :编辑后

const validateWord = async word => {
const input = "https://milog.co.il/" + word;
await new Promise(resolve => {
    chrome.runtime.sendMessage({ input }, messageResponse => {
        const [response, error] = messageResponse;
        const parser = new DOMParser();
        const html = parser.parseFromString(response.body, 'text/html');
        const element = html.querySelector('.sr_e_txt');
        console.log("aaa")
        resolve(element?.innerText !== '');
    });
});
};

validateWord("word")
    .then(data => console.log(data))
        .catch(reason => console.log(reason.message))

它打印 aaa -> bbb -> word.. 我希望先打印“word”,然后等待它完成。

谢谢。


  1. 你不能同时使用回调chrome方法并等待返回值,因为当使用回调时,该方法不会返回 Promise。

  2. Chrome 99之前的bug https://crbug.com/1197387:sendMessage 不会返回 Promise,所以你不能等待它。
    Chrome 99 中已修复。

因此,在早期版本的 Chrome 中,您可以承诺 API:

promisifyApi(chrome.runtime, 'sendMessage');

(async () => {
  const res = await chrome.runtime.sendMessage({ input });
  console.log(res);
})();

function promisifyApi(thisArg, name) {
  const fn = thisArg[name];
  const localStack = new Error('Before calling ' + name);
  thisArg[name] = (...args) => new Promise((resolve, reject) => {
    fn(...args, result => {
      let err = chrome.runtime.lastError;
      if (err) {
        err = new Error(err.message);
        err.stack += '\n' + localStack.stack;
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}

...或者使用回调:

chrome.runtime.sendMessage({ input }, res => {
  // process `res` here
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

chrome 扩展 - 我如何等待 chrome.runtime 函数? 的相关文章

随机推荐