在浏览器中获取带有空响应对象的请求响应?

时间:2020-08-03 09:41:03

标签: javascript html ajax fetch

我正在为firefox构建一个加载项,该加载项只有一个javascript文件。

此javascript文件向网址发出提取请求以检索其html内容。

代码如下:

async function callHtml(url) {
            const options = {
                method: 'GET',
                headers: {'Content-Type': 'text/html', 'Accept': 'text/html'},
                mode: 'no-cors'
            };
           return fetch(url, options)
                .then(function(response) {
                    // When the page is loaded convert it to text
                    console.log('response:', response)
                    return response.text()
                })
                .then(function(html) {
                    // Initialize the DOM parser
                    var parser = new DOMParser();

                    console.log('HTML:', html)
                    // Parse the text
                    var doc = parser.parseFromString(html, "text/html");

                    // You can now even select part of that html as you would in the regular DOM
                    // Example:
                    // var docArticle = doc.querySelector('article').innerHTML;

                    console.log(doc.querySelector('body').innerHTML)

                    //const pay = doc.body.querySelector('a[title="Subscribe Now"]')

                    if(doc.body) {
                        link.style.color = 'green'
                    }
                    return doc.body.innerHTML

                })
                .catch(function(err) {
                    console.log('Failed to fetch page: ', err);
                });
        }

不幸的是,我收到的只是一个没有html内容的空响应对象。

任何人都知道为什么会这样吗?

谢谢!

0 个答案:

没有答案