Chrome扩展运行时.Sendmessage等待响应

Chrome Extension runtime.sendmessage wait for responses

本文关键字:等待 响应 Sendmessage 运行时 扩展 Chrome      更新时间:2023-09-26

我正在开发一个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的响应函数中。唯一的问题是,在我做ajax调用之前,我有sendMessage的3个事件来返回我需要的不同变量,所以不幸的是,这不是一个可行的选择。

是否有任何方法来停止ajax调用,直到所有的sendmessage调用已经完成?

您应该考虑从旧的"在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,将自动传播到其他登录配置文件

一个选择是使用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({});
})