如何通过GreaseMonkey使用jQuery编辑html而不会发生冲突?

时间:2014-07-14 07:16:16

标签: javascript jquery greasemonkey

我试图找到被禁止的字词'在页面上,如果他们发现他们隐藏了他们和页面上的所有图像。隐藏图像与this.$ = this.jQuery = jQuery.noConflict(true);一起正常工作,但是隐藏文字有问题。我使用这段代码来做到这一点:

txt = txt.replace(new RegExp(bannedWords[index], 'gi'),
'<span style=\'color:#000;background-color:#000\' class=\'banned\'>$&</span>');

txt是正文的HTML。它有效,但也与页面的jQuery发生冲突,因为我最终使用了$('body').html(txt);

要重复我的问题,请使用脚本

// ==UserScript==
// @name        Words Filter
// @description Filter words and disable images if it founded
// @include     http://myanimelist.net/*
// @version     3
// @require     http://code.jquery.com/jquery-latest.min.js 
// @grant       none
// ==/UserScript==

//window.addEventListener('load', function ()
document.addEventListener('DOMContentLoaded', 
                           function ()
{
    // Monkey jQuery conflict solving
    this.$ = this.jQuery = jQuery.noConflict(true);
    //var $ = jQuery.noConflict(true);

    //$('img').each(function(){$(this).hide();});
    var txt = $("body").html();
    $("body").html(txt);
    console.log('works'); // it doesn't show anything in the console. Why?
});
<{3>} MyAnimeList page。在页面顶部,您可以看到带有&#34; Profile | Anime | Manga | Community | Industry&#34;的菜单栏。它有下拉列表,我的脚本没有出现。此外,出于某种原因,console.log('works');在控制台中没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

编辑:我在这里找到了一个解决方案:jQuery in Greasemonkey 1.0 conflicts with websites using jQuery

将@grant更改为:

// @grant       GM_log

然后一切顺利。如此试验和测试:

// ==UserScript==
// @name        test
// @namespace   test
// @description Filter words and disable images if it founded
// @include     http://myanimelist.net/*
// @version     3
// @require     http://code.jquery.com/jquery-latest.min.js 
// @grant       GM_log
// ==/UserScript==

//window.addEventListener('load', function ()
document.addEventListener('DOMContentLoaded', 
                           function ()
{
    var _$ = this.jQuery = jQuery.noConflict(true);
    var txt = _$("body").html();
    _$("body").append('<span>SEARCH FOR ME IN SITE!</span>');
console.log('123123123123');
});