我有一个用户脚本,我想在单击链接打开嵌入式网页后注入。具体来说,我想知道我应该如何注入这个脚本:
Array.from(document.querySelectorAll('span')).filter(i => /(\d+)\spoint/.test(i.innerHTML)).forEach(i => i.style.display = 'none');
Array.from(document.querySelectorAll('div')).filter(i => /moreComments-/.test(i.id)).forEach(i => i.querySelector('p').click());
setTimeout(function() {
Array.from(document.querySelectorAll('span')).filter(i => /(\d+)\spoint/.test(i.innerHTML)).forEach(i => i.style.display = 'none');
},7000)
进入所有可嵌入的 Reddit 子页面,即从 subreddit 主页加载的所有链接线程:
说明嵌入式 Reddit 子页面与标准完全加载页面对比的图像
I assume this requires an event listener or MutationObserver
, but I don't know how to go about specifying the solution. Reading the Reddit source is deeply confusing and I'm not a coder. This is just something I think would be useful to know for myself and other everyday web users.
What are the right steps to follow in problem-solving a case like this? What kind of code should I consider?
You need to process the userscript on a selected group of page nodes. Because your code is only executed once per page load event, the nodes that load dynamically later on remain unaffected.
There are several ways to achieve your goal. One of the simplest approaches involves the use of the setInterval
function. This calls your function periodically (by using a reasonable time span, say 500ms). With this function, you have to select the nodes you want and process only new arrival nodes. You can mark your node's DOM objects with something like the _is_processed
property. And finally this can be wrapped into another function, say doForEachOnce
. For example:
function doForEachOnce(list,theFunc) {
list.forEach(i => {
if (!i._is_processed) { i._is_processed = true; return theFunc(i); } else { return null; }
});
}
doForEachOnce(Array.from(document.querySelectorAll('span')).filter(i => /(\d+)\spoint/.test(i.innerHTML)), i => i.style.display = 'none');
doForEachOnce(Array.from(document.querySelectorAll('div')).filter(i => /moreComments-/.test(i.id)), i => i.querySelector('p').click());
setInterval(function() {
doForEachOnce(Array.from(document.querySelectorAll('span')).filter(i => /(\d+)\spoint/.test(i.innerHTML)), i => i.style.display = 'none');
},500);
I tested this userscript successfully with Tampermonkey. It expands all comments, hides the karma on page load, and then hides the karma again for each new arrival. Hope this is what you need.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句