微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

执行 fetch/XMLHttpRequest

如何解决执行 fetch/XMLHttpRequest

我正在编写一个浏览器扩展,在 VK 聊天中用涂鸦替换 gif。算法很简单:在聊天页面上每 500 毫秒,我们浏览每条消息,查找 gif,打开 gif 文档的链接,解析生成的 html 页面并从那里获取到 gif 图像的链接,然后替换在 DOM 结构中带有动画 gif 图像的 gif 文档。我的电脑在 Chrome 和 Firefox 中一切正常。但是,我的朋友在 Firefox 中遇到了非常奇怪的行为。有一段时间,一切正常,但一段时间后,当扩展程序尝试打开 gif 文档的链接时,开始出现错误,只有重新启动浏览器才有帮助。一开始我在代码中使用了fetch函数,在控制台出现了一个错误“TypeError: NetworkError when try to get a resource”。我找不到此错误的任何解决方案。然后我决定尝试 XMLHttpRequest,但它也返回代码为 0 且没有任何描述的错误。请帮我解决这个错误

使用 fetch 的函数代码

let response = await fetch("https://vk.com" + url + hash,{
    }).catch(reason => console.log(count + ": HTTP error: " + reason + "; gif #" + n));
    console.log(count + ": Response code: " + response.status);
    if (response.ok) {
        console.log(count + ": Gif #" + n + " obtained,parsing the gif document page");
        // gif document page
        let html = await response.text();
        let doc = new DOMParser().parseFromString(html,"text/html");
        let img = doc.body.getElementsByClassName("can_zoom")[0];
        // get the gif link
        let src = img.getAttribute("src");
        // cut the parameters
        src = src.substring(0,src.indexOf("?"));
        localStorage.setItem(url,src);
        console.log(count + ": Link to the gif #" + n + ": " + src);
        return src;
    }
    else console.log(count + ": HTTP error: " + response.status + "gif #" + n);

使用 XMLHttpRequest 的函数代码

let getGifImage = (url,hash,n) => new Promise(resolve => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET","https://vk.com" + url + hash);
    xhr.send();
    xhr.onloadend = function () {
        console.log(count + ": Response code: " + this.status);
        if (this.status == 200) {
            console.log(count + ": Gif #" + n + " obtained,parsing the gif document page");
            // gif document page
            let html = xhr.response;
            let doc = new DOMParser().parseFromString(html,"text/html");
            let img = doc.body.getElementsByClassName("can_zoom")[0];
            // get the gif link
            let src = img.getAttribute("src");
            // cut the parameters
            src = src.substring(0,src.indexOf("?"));
            localStorage.setItem(url,src);
            console.log(count + ": Link to the gif #" + n + ": " + src);
            resolve(src);
        } else console.log(count + ": HTTP error (response code: " + this.status + "),gif #" + n);
    };
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。