Created
November 8, 2020 19:24
-
-
Save danielrotaermel/eaa640ec08e869c4b072ee0d44a39edd to your computer and use it in GitHub Desktop.
UserScript: Toggle picture-in-picture in safari (ctrl+p)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Toggle picture-in-picture | |
// @description Toggle picture-in-picture in safari (ctrl+p) | |
// @license MIT | |
// @author Daniel Rotärmel | |
// @namespace https://gist.github.com/danielrotaermel | |
// @match *://*.* | |
// ==/UserScript== | |
document.onkeyup = function(e) { | |
if (e.ctrlKey && e.key == "p") { | |
togglePip() | |
} | |
}; | |
function togglePip() { | |
if (isVideoPresentAndInline()) { | |
document.querySelector('video').webkitSetPresentationMode('picture-in-picture') | |
} else { | |
document.querySelector('video').webkitSetPresentationMode('inline'); | |
} | |
} | |
function isVideoPresentAndInline() { | |
if (document.querySelector('video')!== null && document.querySelector('video').webkitPresentationMode === 'inline') { | |
return true; | |
} else { | |
return false; | |
} | |
} |
Thanks for making this script! I modified it to add a toggle for fullscreen by pressing F
and added floating buttons for iPhones and iPads.
function setButtonStyle(button) {
button.style.position = 'fixed'
button.style.bottom = '5%'
button.style.zIndex = '10'
button.style.width = '5em'
button.style.height = '5em'
button.style.backgroundColor = 'rgb(135 206 235 / 50%)'
button.style.borderRadius = '10%'
}
function togglePiP() {
const element = document.querySelector('video')
if (element) {
element.webkitSetPresentationMode(element.webkitPresentationMode === 'inline' ? 'picture-in-picture' : 'inline')
}
}
function toggleFullscreen() {
const element = document.querySelector('video')
if (element) {
element.webkitSetPresentationMode(element.webkitPresentationMode === 'inline' ? 'fullscreen' : 'inline')
}
}
document.onkeyup = (event) => {
if (event.key === 'p') {
togglePiP()
} else if (event.key === 'f') {
toggleFullscreen()
}
}
// Is touchscreen device
if (navigator.maxTouchPoints > 0) {
let pipButton = document.createElement('button')
let fullscreenButton = document.createElement("button")
pipButton.id = 'pipButton'
fullscreenButton.id = 'fullscreenButton'
setButtonStyle(pipButton)
setButtonStyle(fullscreenButton)
pipButton.innerHTML = '🖼️'
pipButton.style.right = '4%'
fullscreenButton.innerHTML = '📺'
fullscreenButton.style.right = '16%'
document.body.appendChild(pipButton)
document.body.appendChild(fullscreenButton)
pipButton.onclick = (event) => {
togglePiP()
}
fullscreenButton.onclick = (event) => {
toggleFullscreen()
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, you can simplify the script to the following: