Javascript 如何通过浏览器无关的方法检查web应用程序清单是否存在?

Javascript 如何通过浏览器无关的方法检查web应用程序清单是否存在?,javascript,html,node.js,reactjs,progressive-web-apps,Javascript,Html,Node.js,Reactjs,Progressive Web Apps,是否有一种方法可以检查是否存在有效的manifest.json并将其用作应用程序清单(可能带有元标记或其他内容)?我所处的场景是需要在个案基础上推出渐进式web应用程序功能,而不是在整个应用程序中,并且我需要某种条件逻辑来测试manifest.json是否存在,以防止以后出现错误 我曾尝试过使用GET手动检查文件,但由于应用程序的具体和复杂结构,如果我能用另一种方法检查文件是否存在,那将更加谨慎。如果可能的话,我希望避免使用jQuery 谢谢 您可以尝试以下方法: async function

是否有一种方法可以检查是否存在有效的manifest.json并将其用作应用程序清单(可能带有元标记或其他内容)?我所处的场景是需要在个案基础上推出渐进式web应用程序功能,而不是在整个应用程序中,并且我需要某种条件逻辑来测试manifest.json是否存在,以防止以后出现错误

我曾尝试过使用GET手动检查文件,但由于应用程序的具体和复杂结构,如果我能用另一种方法检查文件是否存在,那将更加谨慎。如果可能的话,我希望避免使用jQuery


谢谢

您可以尝试以下方法:

async function doesManifestExistForCurrentPage() {
  const manifestElement = document.querySelector('link[rel="manifest"]');
  if (!manifestElement) {
    return false;
  }
  const manifestUrl = manifestElement.getAttribute('href');
  if (!manifestElement) {
    return false;
  }

  // You could stop here and just return true.
  // If you want to actually see if the manifest file exists on the
  // server, use the following code:
  try {
    const manifestResponse = await fetch(manifestUrl);
    // .ok will be true if fetch() returned a HTTP 2xx response,
    // and false otherwise.
    return manifestResponse.ok;
  } catch (error) {
    // Or return true?
    // Depends on how you want to handle network failures.
    return false;
  }
}
function hasAppManifest() {
    return document.querySelector('link[rel="manifest"]') ? true : false;
}