我创建了一个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)
}
})();
答案 0 :(得分:1)
解决方案是使用jQuery和waitForKeyElements并替换
window.addEventListener('load',
使用
waitForKeyElements(".sc-181ts2x-0",
按钮现在每次都能成功加载