浏览器扩展 service-worker中如何访问http请求
fetch文档:https://developer.mozilla.org/en-US/docs/Web/API/fetch
因为service-worker没有没有运行到普通的环境,普通的node库也用不了,所以需要使用环境方法fetch
fetch('http://example.com/movies.json') .then((response) => response.json()) .then((data) => console.log(data));
manifest中加入(好像也不是太需要)
"host_permissions": [ "http://example.com/" ],
完整post方法
function sendData(data) { let token = "****" let weburl = "http://*****"; let myHeaders = new Headers([["Content-Type", "application/json;charset=UTF-8"]]); myHeaders.append("Authorization", token); let myInit = { method: "POST", headers: myHeaders, body: JSON.stringify(data) }; let request = new Request(weburl, myInit); fetch(request) .then((response) => response.text()) .then((text) => { console.log('text', text) }) }