As mentioned in comments, either overwrite HTMLButtonElement.prototype.click
:
const nativeClick = HTMLButtonElement.prototype.click;
HTMLButtonElement.prototype.click = function(...args) {
console.log('Click');
nativeClick.apply(this, args);
};
document.createElement('button').click();
Or, a slightly different (and less efficient) method would be to overwrite Document.prototype.createElement
such that newly created button
s get listeners attached to them:
const nativeCreateElement = Document.prototype.createElement;
Document.prototype.createElement = function(...args) {
const createdElement = nativeCreateElement.apply(this, args);
if (typeof args[0] === 'string' && args[0].toLowerCase() === 'button') {
createdElement.addEventListener('click', () => {
console.log('Click');
});
}
return createdElement;
}
document.createElement('button').click();
Note that overwriting important built-in objects and methods like this is very hacky and isn't something to be used in serious production code - it's only something to consider when you have no other options, such as in the unusual environment of a userscript.