Fetch api 在 webextensions 中不起作用

Fetch api does not work in webextensions

我正在试验 firefox webextensions。我想在提交表单后使用 fetch API 发出 HTTP 请求。问题是获取请求没有做任何事情。

这是从我的 manifest.json 中提取的数据:

"browser_action": {
    "default_popup": "test.html"
  },
"permissions": [
    "<all_urls>"
 ],

这是我的 test.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<form>
    <button type="submit">Submit</button>
</form>
<script src="test.js"></script>
</body>
</html>

这是我的 test.js:

document.querySelector("form").addEventListener("submit", fetchTest);
function fetchTest() {
    console.log("TEST");

    fetch('https://httpbin.org/get')
        .then(response => response.json())
        .then(response => {
            console.log(response);
            return response;
        })
        .catch(error => console.log(error));
}

当我单击表单的提交按钮时,我看到我的函数 fetchTest 被调用,因为我可以在控制台中看到 "TEST" 消息。但是,我在 "Network" 面板中没有来自浏览器的请求,而且我在控制台中也没有错误,就好像 fetch() 从未发生过一样。

然后,我尝试用 xhr 做同样的事情:

function fetchTest() {
    console.log("TEST");

    const req = new XMLHttpRequest();
    req.open('GET', 'https://httpbin.org/get', false);
    req.setRequestHeader("Content-Type", "application/json");
    req.send(null);
    console.log(req);
}

使用此版本,一切正常。我在 "Network" 面板中看到请求,我的控制台中有数据。

我使用 fetch API 错了吗?

谢谢:)

单击 input of type submit 时,会导致提交:由于未指定其他 URL,并且不存在其他表单元素,页面基本上会重新加载。引用 MDN:

<input> elements of type "submit" are rendered as buttons. When the click event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server.

您的基于 fetch 的解决方案是完全异步的,这意味着您的代码启动,但在完成之前被重新加载中断。

您基于 XHR 的解决方案成功了,因为您调用了 XHR 的同步形式(false);重新加载会停止,直到您的代码完成,然后它仍然会重新加载。

无论如何你都不想重新加载,这会破坏你的 JS 状态;您可以通过从处理程序调用 e.preventDefault() 来阻止它,但从语义上讲,使用 submit 按钮而不是对其语义进行脑部手术更正确 而不是

使用 <input type="button">(或者更好的是,<button>)将是正确(和更清洁)的方法。引用 MDN:

<input type="submit"> buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use <input type="button">, or better still, a <button> element.