Can I close a youtube window using javascript?

45 Views Asked by At

In 2022 ish I used to be able to close a youtube window with javascript

    var openedWindow;

    function openWindow() {
       openedWindow = window.open('https://www.youtube.com/watch?
v=TC1Vfoq3PvU&ab_channel=Historyboy87','_blank', 'location=yes,height=400,width=400,scrollbars=yes,status=yes');
}


function closeOpenedWindow() {
  openedWindow.close();
}

This no longer works. Have tried in Chrome, Firefox and Edge. It will close other websites but not youtube.

1

There are 1 best solutions below

0
PassThru On

You can only EMBED Youtube videos in an iframe and it'll only work if they're not very popular (ie: most music videos with tons of views get blocked).

Here's how I do it, however... it is based on data:text/html to create a "openable" page on the fly and I'm not sure if this still works in the latest browser versions!

It may have been dropped for "security" reasons (read stupid reasons) like so many other wonderful things; and the reason I use a custom browser with older engines. :)

Anyway, in case it does work in the latest commercial browsers, here's how to do it...

let YT='https://www.youtube-nocookie.com/embed/vWq-mIxvH3k'; // change the last part after the slash to play another video

let Url='data:text/html;charset=utf-8,<html><head><title>Embedded video</title></head><body>'+

        '<iframe width="0" height="0" src="'+YT+'" frameborder="0" style="position:absolute;left:0;top:0;width:100%;height:100%;background:black;" allowfullscreen>'+

        '</iframe></body></html>';

let a=document.createElement('A'); 

a.target='_blank'; 

a.href=Url; 

a.click();

NB: Or use window.open() with the URL.

Update:

Here's a modern version using a blob...

let YT='https://www.youtube-nocookie.com/embed/vWq-mIxvH3k'; // change the last part after the slash to play another video

let Url='<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Embedded video</title>'+

        '<style>iframe{position:absolute;left:0;top:0;width:100%;height:99%;background:black;}</style></head><body>'+

        '<iframe width="0" height="0" src="'+YT+'" frameborder="0" allowfullscreen></iframe></body></html>';



let blob=new Blob([Url],{type:"text/html"});

let U=URL.createObjectURL(blob);

let a=document.createElement('A'); 

a.target='_blank'; 

a.href=U; 

a.click();

setTimeout(function(){URL.revokeObjectURL(U);},3000);