Chrome扩展程序runtime.sendmessage等待响应

3

我正在开发一个Chrome扩展程序,但是在使用chrome.runtime.sendMessage函数时遇到了一些问题。

以下是我的代码设置:

chrome.runtime.sendMessage( { method : "getLocalStorage", key: "email" }, function ( response ) {
    console.log( "the response has been received" );
});

console.log( "I am here" );

$.ajax({});

这将打印出:

I am here
the response has been received

所以我的问题是chrome.runtime.sendMessage与代码的其余部分异步运行。所以我可以做的当然是将ajax放在sendMessage的响应函数中。唯一的问题是我有三个sendMessage事件返回不同的变量,我需要在进行ajax调用之前,这不是可行的选择。
是否有任何方法可以阻止ajax调用直到所有的sendMessage调用都已完成?

为什么不统计收到的响应,当你收到3个响应时,执行ajax调用呢? - Lauromine
你是否试图重新发明 chrome.storage API?你在这里查询背景以读取 localStorage吗?如果是的话,我可以展示一个更高效的方法。 - Xan
@xan 是的,我正在调用后台来检索存储在localStorage中的信息。用户输入他/她的电子邮件作为设置,这些设置存储在扩展程序的本地存储中。然后,在执行ajax调用之前,我通过sendMessage检索此信息。所以我的问题现在是,如果我更新了我的电子邮件,并调用ajax调用,它会第一次发送到旧的电子邮件地址,因为它是异步更新的。 - Ole Haugset
2个回答

2
你应该考虑从旧的 "使用 localStorage 存储数据,使用 sendMessage 后台查询" 范式切换到新的 "在任何地方存储数据,使用 chrome.storage" 范式;chrome.storage API 专门为此目的而创建。
缺点是所有访问都变成异步的。但至少你可以优化一下,例如将调用粘合在一起:
chrome.storage.local.get([key1, key2, key3], function(data) {
  // Use data.key1, data.key2, etc.
  $.ajax({});
});

如果还没有默认值,您甚至可以提供默认值:

chrome.storage.local.get({key1: default1, key2: default2, key3: default3}, function(data) {
  // Use data.key1, data.key2, etc.
  $.ajax({});
});

最后但并非最不重要的是,您拥有chrome.storage.sync,它将自动传播到其他已登录的配置文件。


谢谢xan。好的解决方案。我之前不知道storage.local,它完美地解决了我的问题。 - Ole Haugset

1

一个选择是使用 Async.js。然后你可以这样做:

async.parallel([
    function(done) {
        chrome.runtime.sendMessage( { your first message }, function ( response ) {
            done();
        });
    },
    function(done) {
        chrome.runtime.sendMessage( { your second message }, function ( response ) {
            done();
        });
    },
    function(done) {
        chrome.runtime.sendMessage( { your third message }, function ( response ) {
            done();
        });
    }
], function() {
    console.log( "I am here" );
    $.ajax({});
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接