I have a function named close in a js file that can’t be renamed for some reason.
But whenever I want to use window.close function (to close the browser tab) I can’t.
My close function overrides that functionality.
Is there a way to call the main Window.close function to close the browser tab?
<html>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function close() {
alert('hi')
}
function myFunction() {
window.close()
}
</script>
</body>
</html>
Thanks
2
Answers
Assuming you cannot modify the js file that contains the
close
function at all. There’s a trick that allows you to "restore" an overwritten built-in function using a freshwindow
object from an iframe.You can change the
close
variable from being property of the global object to be a global variable only by declaring it withlet
orconst
– see Do let statements create properties on the global object?. So withyour
myFunction
implementationwill just begin to work.
(Of course, this will break all old code that did call
window.close()
and expected it toalert('hi')
– but imo that was a bug anyway).