In my app, I send a request from the client to a node.js server. The server sends an HTML response containing a script:
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 the client I inject the response into document.body using insertAdjacentHTML:
document.body.insertAdjacentHTML('afterbegin', json);
But the script does not execute.
Is it possible to inject 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With