问题
I want to hide the comments with some words inside by a (Tampermonkey) user script. As an example, I tried to apply a script
// ==UserScript==
// @name Hide CNN
// @match http://www.cnn.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_addStyle
// @run-at document-end
// ==/UserScript==
$('div.post-body:contains("Abbas")').hide()
to the page http://www.cnn.com/2014/07/08/world/meast/mideast-tensions/index.html?hpt=hp_t1 with the following code for posts
<div class="post-body">
<header>
...
</header>
<div class="post-body-inner">
<div class="post-message-container" data-role="message-container">
<div class="publisher-anchor-color" data-role="message-content">
<div class="post-message " data-role="message" dir="auto">
<p>Abbas is nothing but puppet dog of Western savages and Nazis who want to enslave entire world.</p>
</div>
...
</div>
But the script does not seem to do anything. What am I doing wrong? Is it possible at all to filter a dynamically-loaded part of a webpage with a user script?
UPD: The problem is that comments are loaded in the iframe from another domain. How do I hide a child node of such an iframe with Tampermonkey? Do I need to use GM_xmlhttpRequest
somehow?
回答1:
Disqus-powered comments are typically loaded in an <iframe>. So rather than set your script to run on the main site, you set it to run on the iframe src
URL. In this case, http://disqus.com/embed/comments/...
Also, these comments are AJAX driven. So you must use AJAX savvy techniques.
A script like this should work (selector might need tuning):
// ==UserScript==
// @name Hide select CNN comments
// @match http://disqus.com/embed/comments/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
//--- Only run on comments for CNN pages
if (/&f=cnn&/i.test (location.search) ) {
waitForKeyElements ('li.post:contains("Abbas")', hideComment);
}
function hideComment (jNode) {
jNode.hide ();
}
来源:https://stackoverflow.com/questions/24633393/userscript-to-hide-a-child-node-of-a-cross-domain-iframe