Я создал скрипт Tampermonkey, который внедряет кнопку в веб-страницу и загружает текстовый файл, когда вы нажимаете на нее. Все отлично работает Но если вкладка загружается в фоновом режиме (например, вы открываете новую вкладку, не переходя на нее), кнопка не появляется.
Нет разницы между
// @run-at document-idle
и
// @run-at document-start
но если я вставлю кнопку в статический элемент
document.body.appendChild(button)
вместо
document.getElementsByClassName("sc-181ts2x-0")[0].appendChild(button)
работает 100% времени в фоновом режиме
Я предполагаю, что это потому, что элемент, к которому я пытаюсь добавить кнопку, не существует, когда он загружается, но это происходит только тогда, когда вкладка находится в фоновом режиме и
// @run-at document-idle
должен убедиться, что он запускается только после загрузки каждого
// @name Pixiv Description Downloader
// @namespace http://tampermonkey.net/
// @version 0.5
// @description Downloads captions/descriptions from pixiv to a work_title(pixiv_id).txt. The format is the same as that of PXdownloader, which does not support captions.
// @author UglyGoblin
// @include https://www.pixiv.net/member_illust.php?*
// @grant none
// @require https://raw.githubusercontent.com/eligrey/FileSaver.js/master/dist/FileSaver.js
// @run-at document-idle
// ==/UserScript==
(function() {
'use strict';
window.addEventListener('load', () => {
addButton('\<b\>↓ Description \<\/b\>', downloadDescriptionFN)
})
//insert button
function addButton(text, onclick, cssObj) {
cssObj = cssObj || {position: 'relative', right:'10px', top:'2px','z-index': 3}
let button = document.createElement('button'), btnStyle = button.style
//add button next to PXdownloader button
document.getElementsByClassName("sc-181ts2x-0")[0].appendChild(button)
button.innerHTML = text
button.onclick = onclick
//make button background transparent
button.style.background = "none";
button.style.border = "none";
Object.keys(cssObj).forEach(key => btnStyle[key] = cssObj[key])
return button
}
//actual function to download on button press
function downloadDescriptionFN() {
//get url of current tab
var url = window.location.href;
//get the pixiv id from url
var pixivID = url.split('illust_id=')[1];
//get title of artwork
var title = document.getElementsByClassName("sc-1u8nu73-3 igWZKS")[0].textContent;
//add pixiv it to title => title(pixiv_id).txt
var textfile = title.concat('\(',pixivID,'\).txt');
//get captions as html
var rawHTML = document.getElementsByClassName("_3BeBvbu");
//replace <br> with \n
var textWithLineBreaks = rawHTML[0].innerHTML.replace(/\<br\>/gi,"\n");
//add title as title to textfile (for some reason needs 2 linebreaks to work)
var finalTXT = title.concat("\n","\n",textWithLineBreaks);
//create new blob with content of captions
var blob = new Blob([finalTXT], {type: "text/plain;charset=utf-8"})
//save the blob as textfile with the name title(pixiv).txt
saveAs(blob, textfile)
}
})();