Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: prevent function overriding by getting the native function

Is it possible to prevent a javascript function to be redefined by getting back the standard function.

Let me explain myself :

I have a module that is supposed to detect browser extensions that manipulate the DOM.

However, any native function can be redefined by that extension.

Therefore, i am trying to get the native functions back through an iframe element.

In the following code i do that but am getting an illegal invocation on the observe method.

( function() { 

//protection against overriding of MutationObserver and XMLHttpRequest method
var iframe_tag = document.createElement('iframe');
document.body.appendChild(iframe_tag);
window.MutationObserver = iframe_tag.contentWindow.MutationObserver;
window.XMLHttpRequest = iframe_tag.contentWindow.XMLHttpRequest;

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
  //Here we detected a change....
};

// binding to window object --> does not work Illegal invocation
MutationObserver.prototype.observe = MutationObserver.prototype.observe.bind(this);

// Create an observer instance linked to the callback function
var bodyobserver = new MutationObserver(callback);

// Start observing the target node for configured mutations
bodyobserver .observe(document.body, config);


} ) ();

Is this the way to do it / What am i doing wrong ?

like image 899
Laurent B Avatar asked Jul 28 '26 11:07

Laurent B


1 Answers

You should override the entire prototype with

window.objectToOverride.prototype = Object.create(iframe.objectToOverride.prototype)

Result:

( function() { 

//protection against overriding of MutationObserver and XMLHttpRequest method
var iframe_tag = document.createElement('iframe');
document.body.appendChild(iframe_tag);
window.MutationObserver.prototype = Object.create(iframe_tag.contentWindow.MutationObserver.prototype);
window.XMLHttpRequest.prototype = Object.create(iframe_tag.contentWindow.XMLHttpRequest.prototype);

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
  //Here we detected a change....
};

// binding to window object --> does not work Illegal invocation
// Not needed anymore
//MutationObserver.prototype.observe = MutationObserver.prototype.observe.bind(this);

// Create an observer instance linked to the callback function
var bodyobserver = new MutationObserver(callback);

// Start observing the target node for configured mutations
bodyobserver.observe(document.body, {});


} ) ();
like image 187
klugjo Avatar answered Jul 30 '26 23:07

klugjo