Woah! I've been enlightened by my husband a neat little trick to get a floating video player off any website that will stay on top of all your windows while you're interacting with other sites, applications, etc. No more resizing my windows, no more playing videos on a separate monitor/device. Just a simple click to pop out the video and continue my work.
Setup & Usage
For everyone who wants this now, here's how:
- In Chrome, open up a video, like this YouTube video 😉 and replace the URL with
javascript:document.getElementsByTagName('video')[0].requestPictureInPicture();
Once the video pops out, you can move it, resize it, etc!
But remembering that bit of code and typing it into your URL bar every time seems a bit annoying right? So let's save it as a bookmarklet.
- In Chrome, make a new bookmark. (Ctrl + Shift + O, then click on the three dots in the upper-righthand corner and click "Add New Bookmark").
- Add a name (like "Floating Player") and set the URL to
javascript:document.getElementsByTagName('video')[0].requestPictureInPicture();
- Great! Now back to the video 😉. This time click on your bookmarklet to pop the video out!
So How Does it Work?
Essentially, we'll are executing the JavaScript directly in your browser to look for any <video>
elements and then on the first <video>
element, we're leveraging the Picture-in-Picture API that allows websites to create a floating video window that stays on top of other windows and applications. Up until yesterday, I haven't heard of running JavaScript directly in the URL bar or the Picture-in-Picture API, so let's break it down together.
1. javascript:
As I mentioned, you can use the javascript:
prefix in a URL to tell the browser to execute the following code as JavaScript instead of navigating to the web address.
Let's try it out. In the URL bar, type javascript:console.log('hello world')
and then inspect the page to see it in your console log. Neat right?
2. document.getElementsByTagName('video')[0]
Now that we're requesting to execute JavaScript, let's run the getElementsByTagName('video')
method on the document
to get an HTMLCollection of the elements with a <video>
tag. Since it will return an array-like object, we will use bracket notation [0]
to target the first <video>
returned by the DOM (Document Object Model) API.
3. requestPictureInPicture()
Great now that we have the video element, you can add the requestPictureInPicture()
method to request the display the video in picture-in-picture mode, which we've seen will return a floating player that stays on top of websites and applications.
4. Bookmarklets
Although we've ran everything so far in this example in the URL bar, as we've done earlier in the setup/usage, we can set the snippet as a bookmark to execute to execute JavaScript making it a bookmarklet.
And that's it! Anyways go forth and enjoy!
Top comments (0)