Skip to content

Instantly share code, notes, and snippets.

@yoni-g
Last active March 3, 2021 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoni-g/0ae03fd9ec21e62a48555a740caae166 to your computer and use it in GitHub Desktop.
Save yoni-g/0ae03fd9ec21e62a48555a740caae166 to your computer and use it in GitHub Desktop.
How to force close an opened download file (pdf) tab or page that opened by a link?
function openPage(url) {
window.setTimeout(function () {
openWindow(url);
} ,500);
}
function openWindow(url) {
var tab = window.open(url);
if (!url.location.pathname.includes('pdf')){
setTimeout(function () {
tab.close();
}, 3000);
}
}
@yoni-g
Copy link
Author

yoni-g commented Apr 18, 2017

I have written this short js code that makes the job. The script can be editable with how much time to delay the open and close of the page. Also i have added an ‘if’ condition that if the file opened is a pdf file, it will not close the tab.
instructions:

  1. First include it to the html.
  2. Add an onclick attr to the tag. inside, you put the “openPage()” function with the url (with single quotes surrounding it!);
  3. In the href attribute put “javascript:void(0);”;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment