简体   繁体   中英

Can I use Element.insertAdjacentHTML() to insert tag script

i have request to node.js from client. Node.js response string

app.post('/verify',cors(issue2options), async (req, res) => {
let auth = await mongo({
    input:'express app',
    data:req.body['auth']['address'],
    type:'verify'
},'get', 'type')

if(empty(auth)){
    res.send(JSON.stringify(`

                                <div id="registration" slot="varan-about"> 
                                Войдите под аккаунтом администратора
                                <script type="module">

                                 console.log('sssss') 

                                <\/script>
                                </div>`))
}else{
    res.send(true)
}

}) On client I insert string to document['body']

 document['body'].insertAdjacentHTML('afterbegin', `${json}`);

But then i insert string script no work.

Is it possible to insert a script using this method ?

From the official HTML5 spec :

script elements inserted using innerHTML do not execute when they are inserted.

Inserting the adjacent HTML is the same as modifying innerHTML of a specific DOM element.

If you really want to provide a mixture of html, css and javascript back from your server, you might want to put each part into a respective property. For example: {"js": "<Some js here">, "html": "<Some markup here>", "css": "<Some styles here>"} Then, on the client side, you can create a script tag and inline your logic to it:

var script = document.createElement('script');
script.textContent = data.js;
document.body.appendChild(script);

The style could be handled in the similar fashion:

var style = document.createElement('style');
style.textContent = data.css;
document.head.appendChild(style);

Finally, the markup could be changed via innerHTML but keep in mind that this will not remove any event handlers attached to the DOM elements that will have been replaced by new elements after parsing new HTML:

var someNode = document.querySelector('<some selector>');
someNode.innerHTML = data.html;

As many of the answers have pointed out, attempting to insert the script directly as text will prevent it from running. Here is one method that works:

const divFragment = document.createRange().createContextualFragment(`${json}`);
document.body.prepend(divFragment);

Sources:

Yes you can user insertAdjacentHTML with any
for more infformation visit this page
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

in you implementation, I think you don't have to create DOM on server side, just get the response and create DOM on client side in JS

like

 var p = document.createElement("p"); p.text = 'My new Paragraph :)' function myFunction() { var h = document.getElementById("myH2"); h.insertAdjacentHTML("afterend", p.text); }
 <h2 id="myH2">My Header</h2> <button onclick="myFunction()">Insert a paragraph</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM