QuerySelector() on DOMParser() object results in null

Asked 1 years ago, Updated 1 years ago, 351 views

I would like to fetch the contents of a specific selector by fetching the web page.
However, if you execute the code below, domTarget is null.
How can I get the contents of the selector?

 document.addEventListener('DOMContentLoaded', function(){
    document.querySelector('.btn').addEventListener('click', clickHandler);
});

async function clickHandler(e){
    const data = wait fetch('https://www.google.com/search?q=a')
    consthtml=data.text()
    constdom = new DOMParser().parseFromString(html, 'text/html');
    const domTarget=dom.querySelector('#result-stats')
}
<!DOCTYPE html>
<html>
    <head>
        <scriptsrc="search.js"></script>
    </head>
    <body>
        <button type="button" class="btn">RUN</button>
    </body>
</html>
{
    "name": "Sample",
    "version": "1.0.0",
    "manifest_version"—3,
    "permissions": ["activeTab", "scripting",
    "action": {
        "default_popup": "content.html"
    }
}

javascript chrome-extension

2022-10-31 00:00

1 Answers

host_permissions is not set in manifest.json in the questionnaire, so it seems that there was a CORS error at that time, but

"host_permissions":[
        "https://www.google.com/"
    ]

said he.

const data=wait fetch('https://www.google.com/search?q=a')
    consthtml=data.text()

However, this Response.text() is resolved asynchronously, i.e., Promise.So you need to wait

async function clickHandler(e){
    const data = wait fetch('https://www.google.com/search?q=a')
    consttml = wait data.text()
    constdom = new DOMParser().parseFromString(html, 'text/html');
    const domTarget=dom.querySelector('#result-stats')
    console.log(domTarget)
}

domTarget


2022-10-31 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.