Skip to content

Instantly share code, notes, and snippets.

@emonkak
Last active September 10, 2021 05:35
Show Gist options
  • Save emonkak/bd8d5330290af5372e6621439ade64a8 to your computer and use it in GitHub Desktop.
Save emonkak/bd8d5330290af5372e6621439ade64a8 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name cockpit-for-pixiv simple download extension
// @namespace Violentmonkey Scripts
// @match https://www.pixiv.net/*
// @grant GM_download
// @version 1.0
// @author -
// @description 9/2/2021, 1:18:12 AM
// ==/UserScript==
(() => {
const CLASS_NAME = '__cockpit-for-pixiv-simple-download';
function appendDownloadButton(img) {
const a = document.createElement('a');
a.className = CLASS_NAME;
a.href = img.src;
a.style = `
display: flex;
align-items: center;
justify-content: center;
position: absolute;
bottom: 40px;
left: 50%;
width: 48px;
height: 48px;
transform: translateX(-50%);
z-index: 1;
background-color: rgba(11, 19, 43, 0.6);
color: #ffffff;
border-radius: 50%;
`;
a.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"></path>
</svg>
`;
a.onclick = (event) => {
event.preventDefault();
event.stopPropagation();
downloadUrl(event.currentTarget.href);
};
img.parentNode.appendChild(a);
}
function handleKeydown(event) {
if (event.key === 'd') {
event.preventDefault();
event.stopPropagation();
const downloadButtons = Array.from(document.querySelectorAll('.' + CLASS_NAME));
for (downloadButton of downloadButtons) {
const bounds = downloadButton.getBoundingClientRect();
if (0 <= bounds.top && bounds.top <= window.innerHeight) {
downloadUrl(downloadButton.href);
break;
}
}
}
}
function downloadUrl(url) {
const name = new URL(url).pathname.split('/').slice(-1)[0];
const headers = { 'Referer': location.href };
GM_download({ url, name, headers });
}
const target = document.getElementById("cockpit-for-pixiv");
if (!target) {
console.error('#cockpit-for-pixiv element cannot be found.');
return;
}
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
const el = mutation.target;
if (el.nodeName === 'IMG' && el.src.startsWith('https://i.pximg.net/img-original/')) {
appendDownloadButton(el);
}
}
});
observer.observe(target, { attributes: true, subtree: true });
window.addEventListener('keydown', handleKeydown);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment