javascript - 来自 Chrome 扩展程序的多个 Web 服务调用

标签 javascript jquery google-chrome-extension

我正在使用 JQuery 2.2.0 编写我的第一个 JavaScript Chrome 扩展,它基本上获取当前 URL 并轮询一些不同的 Web 服务以查看它们是否有 URL 记录。如果存在,我会在 DOM 中添加一个文本链接。这是一个简化的工作版本:

// Does the provided URL exist?
function url_exists(url) {
    var h = new XMLHttpRequest();
    h.open('HEAD', url, false);
    h.send();
    return h.status!=404;
}

// Display a link to the database record URL in the DOM
function display_database_link(url) {
  $('body').prepend('<a href="' + url + '">Link</a>');
}


// Get the current URL
var url             = window.location.href;
var database_number = 0;

// See if this URL exists in one of our databases via the API

// Does the URL exist in database 1?
if (url_exists("https://api.database1.com/urls/" + url)) {
  database_number = 1;
}

// Does the URL exist in database 2?
else if (url_exists("https://api.database2.com/urls/" + url)) {
  database_number = 2;
}

if (database_number > 0) {
  display_database_link("https://api.database" +  database_number + ".com/urls/" + url))
}

我所拥有的有效,但我想知道是否:

  1. 有一种方法可以同时多次调用 url_exists,并且

  2. 是否有办法异步执行此操作。

如果有人可以回复相关文档或示例的链接,我将非常感激!

最佳答案

有几个很棒的 es2015 功能可以让这一切变得美好而简单:fetchpromises 。您必须进行一些调整,但类似这样的操作应该可行。

// Array of API endpoints to to make requests to
let url = window.location.href;
let database_urls = ["https://api.database1.com/urls/", "https://api.database2.com/urls/"];

// Promise.all will take an array of promises and perform all of them, and `then` process all results at the end
Promise.all(database_urls.map(database_url =>
  // Make an HTTP request to the endpoint, and `then` get the status code from the response
  fetch(database_url + url).then(response => response.status)
// Once `all` promises are resolved, `then` iterate over the resulting statuses
)).then(statuses => {
  // Reduce `statuses` to a count of how many are not 404s
  let existCount = statuses.reduce((prev, curr) => {return curr == 404 ? prev : prev + 1}, 0);
  // Call method to display link if existsCount is > 0
});

关于javascript - 来自 Chrome 扩展程序的多个 Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542289/

相关文章:

javascript - 在 Chrome JS 调试器中,如何打印对象的所有属性?

javascript - 如何使用 css 按钮调用 jquery 函数?

google-chrome - 如何查看/检查 Chrome 扩展的本地存储?

javascript - 如何使用本地存储在另一个页面上显示上传的图像?

javascript - FlowType 包装获取而不丢失默认类型注释

php - 使用 jQuery 自动创建 div 并从 mysql 插入数据

javascript - 在时间用完后重新打开 Chrome 时,Chrome 扩展程序警报会关闭吗?

google-chrome-extension - 注入(inject)的 iframe 和内容脚本之间的通信——通过后台页面传递消息

php - 获取 Div 的宽度并根据元素数量限制 mySQL 查询?

javascript - 删除输入字段的内容jQuery