I work with Microsoft Edge version 120.0.2210.91 (Official build) (64-bit).
I have created this modal with an X button that if clicked, should close the modal.
document.body.insertAdjacentHTML('beforeend', `
<div class="modal_wrapper">
<span class="modal_closing_button" onclick="this.parentNode.style.display = 'none';">X</span>
<div class="modal_message">
</div>
</div>
`)
newStyle = document.createElement("style");
newStyle.type = "text/css";
newStyle.innerHTML +=`
.modal_wrapper {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
font-weight: bold;
background: green;
}
.modal_closing_button {
display: block;
position: absolute;
text-align: right;
color: #fff;
font-size: 5em;
top: 1em;
right: 1em;
}
.modal_message {
padding: 25px 25px 0 25px;
margin: 0 0 10px 0;
font-size: 20px;
display: block;
color: #fff;
}
`;
document.head.appendChild(newStyle);
When I click the X button I get this error:
Refused to execute inline event handler because it violates the following Content Security Policy directive:
âscript-src âselfâ blob: filesystem:â.
Either the âunsafe-inlineâ keyword, a hash (âsha256-âŚâ), or a nonce (ânonce-âŚâ) is required to enable inline execution.
Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the âunsafe-hashesâ keyword is present.
I didnât quite understand this error, but from this Stack Overflow discussion I understand that onclick
event listeners are often âinvalidâ and addEvenetListener('click', FUNCTION)
should normally be used instead.
This JS code practically works.
document.body.insertAdjacentHTML('beforeend', `
<div class="modal_wrapper">
<span class="modal_closing_button">X</span>
<div class="modal_message">
</div>
</div>
`)
newStyle = document.createElement("style");
newStyle.type = "text/css";
newStyle.innerHTML +=`
.modal_wrapper {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
font-weight: bold;
background: green;
}
.modal_closing_button {
display: block;
position: absolute;
text-align: right;
color: #fff;
font-size: 5em;
top: 1em;
right: 1em;
}
.modal_message {
padding: 25px 25px 0 25px;
margin: 0 0 10px 0;
font-size: 20px;
display: block;
color: #fff;
}
`;
document.head.appendChild(newStyle);
window.addEventListener('click', ()=>{
document.querySelector('.modal_closing_button').parentNode.remove();
});
Anyway, although it seems to me to work fine, I get this console error after running it:
Uncaught TypeError: Cannot read properties of null (reading âparentNodeâ)
at :51:52
What have I done wrong and please share if you will do anything here slightly different.