简体   繁体   English

仅当用户脚本看到触发词时,才如何替换网站上的文本?

[英]How do I replace text on website only if the userscript sees a trigger word?

I want my userscript to replace word "A", on a page, with word "B", unless word "C" is present. 我希望我的用户脚本将页面上的单词“ A”替换为单词“ B”, 除非出现单词“ C”。
If "C" is present, then I want to replace "A" with "D" instead. 如果存在“ C”,那么我想将“ A”替换为“ D”。

For example, 例如,

  1. Normally, it would replace Cat with Feline . 通常情况下,它会取代CatFeline
  2. But, if the userscript sees the word Kitten on the webpage, it would instead change Cat to Meow . 但是,如果用户脚本在网页上看到“ Kitten ”一词,它将改为将Cat更改为Meow
  3. Obviously, it should do the same with multiple other word sets, if I want it to. 显然,如果我想要的话,它应该与多个其他单词集相同。

I found this old userscript written by Joe Simmons ; 我发现了这个由乔·西蒙斯(Joe Simmons)编写的旧用户脚本 see the relevant code, below. 请参阅下面的相关代码。 Although it works extremely well, How do I add the conditional functionality? 尽管效果非常好,但如何添加条件功能?

(function () { 'use strict';
    var words = {
        // Syntax: 'Search word' : 'Replace word',
        'your a':       'you\'re a',
        'imo':          'in my opinion',
        'im\\*o':       'matching an asterisk, not a wildcard',
        '/\\bD\\b/g':   '[D]',

        ///////////////////////////////////////////////////////
        '': ''
    };

    var regexs = [],
        replacements = [],
        tagsWhitelist = ['PRE', 'BLOCKQUOTE', 'CODE', 'INPUT', 'BUTTON', 'TEXTAREA'],
        rIsRegexp = /^\/(.+)\/([gim]+)?$/,
        word, text, texts, i, userRegexp;

    // prepareRegex by JoeSimmons
    // used to take a string and ready it for use in new RegExp()
    function prepareRegex (string) {
        return string.replace (/([\[\]\^\&\$\.\(\)\?\/\\\+\{\}\|])/g, '\\$1');
    }

    // function to decide whether a parent tag will have its text replaced or not
    function isTagOk (tag) {
        return tagsWhitelist.indexOf (tag) === -1;
    }

    delete words['']; // so the user can add each entry ending with a comma,
    // I put an extra empty key/value pair in the object.
    // so we need to remove it before continuing

    // convert the 'words' JSON object to an Array
    for (word in words) {
        if (typeof word === 'string' && words.hasOwnProperty (word) ) {
            userRegexp = word.match (rIsRegexp);

            // add the search/needle/query
            if (userRegexp) {
                regexs.push (
                    new RegExp (userRegexp[1], 'g')
                );
            }
            else {
                regexs.push (
                    new RegExp (prepareRegex (word)
                        .replace (/\\?\*/g, function (fullMatch) {
                            return fullMatch === '\\*' ? '*' : '[^ ]*';
                        } ),
                        'g'
                    )
                );
            }

            // add the replacement
            replacements.push(words[word]);
        }
    }

    // do the replacement
    texts = document.evaluate ('//body//text()[ normalize-space(.) != "" ]', document, null, 6, null);
    for (i = 0; text = texts.snapshotItem (i); i += 1) {
        if (isTagOk (text.parentNode.tagName) ) {
            regexs.forEach (function (value, index) {
                text.data = text.data.replace (value, replacements[index]);
            } );
        }
    }
} () );

You could abuse the execution order by creating a kitten filter that would trigger before the cat filter. 您可以通过创建一个小猫过滤器来滥用执行顺序,该小猫过滤器将在cat过滤器之前触发。

var words = {
///////////////////////////////////////////////////////
    // Syntax: 'Search word' : 'Replace word',
    '/(kitten.*)?Cat(.*kitten)?/gi' : 'Meow',
    'Cat'                           : 'Feline',
///////////////////////////////////////////////////////
};

It's certainly less annoying than implementing a callback. 它肯定比实现回调更令人讨厌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM