I am trying to write an extension that tries to block file chooser from popping up when the user clicks on an element, with the goal to prevent file input.
This is what my content script looks like:
content.js
function preventFileChooser(event) {
event.stopPropagation();
event.preventDefault();
}
document.addEventListener('click', function(event) {
if (event.target && event.target.nodeName === 'INPUT' && event.target.type === 'file') {
preventFileChooser(event);
}
}, true);
While this works for most cases, it fails when the input element is dynamically created (but not appended to the body) and a click event is dispatched upon it. An example of such a page:
test.html
<!DOCTYPE html>
<html>
<head>
<script src='test.js'></script>
</head>
<body>
<button id='btn'>click</button>
</body>
</html>
test.js
document.addEventListener('click', (e)=>{
if(e.target.id==='btn'){
var ele = document.createElement('input');
ele.type='file';
ele.addEventListener('change', async (e) => {
//Here, using a package such as https://www.npmjs.com/package/file-selector allows the page to convert the file input into File objects.
})
ele.dispatchEvent(new MouseEvent('click'));
}
})
jsFiddle : https://jsfiddle.net/yu0wjvb4/
In a page such as this, when the button is clicked, the content script fails to listen to the dispatched click event on the dynamically created (but not appended) input element and therefore fails to prevent the file chooser from opening.