Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve/restore native javascript function after being overwritten

Tags:

javascript

Let's say we run the following line of code

Object.defineProperty(HTMLElement.prototype, 'click', {value: null});

Is there any way whatsoever to retrieve/restore the original click function?

And yes, I am aware that it is possible to trigger a click event through dispatchEvent, however it is possible to patch that up in a similar way. What I am asking about whether it is possible to restore the click event or somehow trigger that click function after it has been overwritten like that. Do assume that that line of code was the very first line of code being run.

like image 579
David Mulder Avatar asked Sep 11 '25 21:09

David Mulder


1 Answers

A way to restore the original implementation is by getting a reference to the namespace of another frame, and re-use the implementation from that frame. This method does not work if the page is running in a sandbox without the allow-same-origin flag though.

// Create a new execution context and get the implementation of "click".
var frame = document.createElement('iframe');
frame.sandbox = 'allow-same-origin';
document.body.appendChild(frame);
var click = frame.contentWindow.HTMLAnchorElement.prototype.click;
frame.remove();

var a = document.createElement('a');
a.href = 'https://example.com';
document.body.appendChild(a);

// Use the implementation.
click.call(a);

a.remove();
like image 163
Rob W Avatar answered Sep 14 '25 10:09

Rob W