How to avoid shadowing the window.close function?

84 views Asked by At

I have a function named close in a js file that can't be renamed for some reason. Now 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?

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>

<script>
    function close() {
        alert('hi')
    }
    function myFunction() {
        window.close()
    }
</script>

</body>
</html>

2

There are 2 answers

1
Bergi On BEST ANSWER

You can change the close variable from being property of the global object to be a global variable only by declaring it with let or const - see Do let statements create properties on the global object?. So with

/* do not change to function declaration or var, as that would break `window.close`! */
const close = function close() {
    alert('hi')
};

your myFunction implementation

function myFunction() {
    window.close()
}

will just begin to work.

(Of course, this will break all old code that did call window.close() and expected it to alert('hi') - but imo that was a bug anyway).

1
Hao Wu On

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 fresh window object from an iframe.

You can't see it's working here because the emulator is running inside of an iframe.

<html>

<body>
  <button onclick="myFunction()">Click me</button>

  <script>
    function close() {
      alert('hi')
    }

    function myFunction() {
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.append(iframe);

      // calling original window.close function
      iframe.contentWindow.close.call(window);

      iframe.remove();
    }
  </script>

</body>

</html>