Page 1 of 1

Prevent script execution with MutationObserver in Firefox?

Posted: Mon May 03, 2021 4:30 pm
by barbaz
(Spinning off from viewtopic.php?p=103934#p103934 to keep that thread on topic -)
Giorgio Maone wrote:
Mon May 03, 2021 2:22 pm
MutationObserver callbacks are called after the DOM is modified (but before most side effects of that modification, like repaints or script parsing and execution, happen).
How do you get MutationObserver to prevent script execution in Firefox? This example doesn't for me -

Code: Select all

data:text/html,<meta charset="utf-8"><script>let m=new MutationObserver((ra)=>{for(let r of ra){for(let n of r.addedNodes){if(n.tagName=='SCRIPT')n.remove();}}});m.observe(document.documentElement,{childList:true,subtree:true});window.addEventListener('DOMContentLoaded',(ev)=>{let s=document.createElement('script');s.textContent='alert(1)';document.body.appendChild(s);},false);</script>
(IIRC from other examples, in Chromium this would work, i.e. the alert would not show.)

Re: Prevent script execution with MutationObserver in Firefox?

Posted: Mon May 03, 2021 7:55 pm
by Giorgio Maone
It doesn't work for inline scripts, it should work for loaded scripts.
For the former you can use onbeforescriptexecute though (Firefox only).

Re: Prevent script execution with MutationObserver in Firefox?

Posted: Tue May 04, 2021 5:50 pm
by barbaz
Thanks Giorgio for the response!
Giorgio Maone wrote:
Mon May 03, 2021 7:55 pm
it should work for loaded scripts.
It doesn't for me, putting this page on my local server -

Code: Select all

<meta charset="utf-8">
<script>
let m=new MutationObserver((ra) => {
  for (let r of ra) {
    for (let n of r.addedNodes) {
      if (n.tagName == 'SCRIPT') n.remove();
    }
  }
});
m.observe(document.documentElement,{childList:true,subtree:true});

window.addEventListener('DOMContentLoaded',(ev) => {
  let s=document.createElement('script');
  s.src='some.js';
  document.body.appendChild(s);
},false);</script>
some.js

Code: Select all

alert('It Did Load And Run!!!!!!!!!!!!!!!!');
Giorgio Maone wrote:
Mon May 03, 2021 7:55 pm
For the former you can use onbeforescriptexecute though (Firefox only).
That's what I'm currently using for the project where I need this. But I'm uneasy about that because beforescriptexecute is slated for removal Image

Re: Prevent script execution with MutationObserver in Firefox?

Posted: Tue May 04, 2021 7:45 pm
by Giorgio Maone
Yes, mutation observers for that purpose seem to work on Chrome only. Using beforescriptexecute as a fallback seems the only option (other than inserting a <meta> CSP) on Firefox.