Skip to content

Instantly share code, notes, and snippets.

@theuves
Last active July 20, 2019 00:37
Show Gist options
  • Save theuves/c310bbc41c654f2b6ae4d8388fddf653 to your computer and use it in GitHub Desktop.
Save theuves/c310bbc41c654f2b6ae4d8388fddf653 to your computer and use it in GitHub Desktop.
Coming soon...
/**
* A bookmarklet to generate a QR code from the current page URL.
*
* @author Matheus Alves
* @license MIT
*/
(() => {
function getQrCodeUrl(value, size) {
const url = new URL('https://chart.googleapis.com/chart')
url.searchParams.append('chs', `${size}x${size}`)
url.searchParams.append('cht', 'qr')
url.searchParams.append('choe', 'UTF-8')
url.searchParams.append('chl', value)
return url.href
}
function createSpinnerKeyframes(id) {
const styleElement = document.createElement('style')
const styleCode = `
@keyframes spinner_${id} {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`
styleElement.innerHTML = styleCode
document.head.appendChild(styleElement)
}
function showQrCode() {
const SIZE = 300
const spinnerId = Math.random().toString().substr(2)
// elements
const container = document.createElement('div')
const closeButton = document.createElement('button')
const itemContainer = document.createElement('div')
const spinner = document.createElement('div')
const qrCodeImage = document.createElement('img')
createSpinnerKeyframes(spinnerId)
// styles
container.style = `
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 9999999999;
transition: all 1s linear;
background-color: rgba(255, 255, 255, .9);
`
closeButton.style = `
all: unset;
position: fixed;
top: 10%;
right: 10%;
font-size: 3em;
cursor: pointer;
color: #333;
`
itemContainer.style = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
`
spinner.style = `
width: ${SIZE / 5}px;
height: ${SIZE / 5}px;
border-radius: 100%;
border: solid 5px black;
border-right-color: transparent;
animation: spinner_${spinnerId} .8s linear infinite;
background-color: transparent;
`
qrCodeImage.style = `
border-radius: 5px;
box-shadow: 0 0 30px 0 #ddd;
`
container.appendChild(closeButton)
container.appendChild(itemContainer)
closeButton.innerHTML = '×'
closeButton.addEventListener('click', () => container.remove())
itemContainer.appendChild(spinner)
qrCodeImage.src = getQrCodeUrl(window.location.href, SIZE)
qrCodeImage.addEventListener('load', () => {
itemContainer.innerHTML = ''
itemContainer.appendChild(qrCodeImage)
})
document.body.appendChild(container)
}
window.addEventListener('keydown', ({ ctrlKey, altKey, code }) => {
if (ctrlKey && altKey && code === 'KeyQ') {
showQrCode()
}
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment