如何在 JavaScript 中访问 Chrome 拼写检查建议

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30704264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:33:52  来源:igfitidea点击:

How to access Chrome spell-check suggestions in JavaScript

javascriptgoogle-chromechromiumspell-checking

提问by

How does one detect a spelling mistake inside a textarea in JavaScript? Is there an event associated with this? How do I access Chrome's spell-check suggestions for a misspelled word?

如何检测 JavaScript 文本区域内的拼写错误?是否有与此相关的事件?如何访问 Chrome 对拼写错误的单词的拼写检查建议?

回答by Ninjakannon

How do I access Chrome's spell-check suggestions for a misspelled word?

如何访问 Chrome 对拼写错误的单词的拼写检查建议?

To the best of my knowledge, you cannot. To answer more fully, I'll also mention related issues:

据我所知,你不能。为了更全面地回答,我还将提及相关问题:

Is there an event associated with this?

是否有与此相关的事件?

No, nor does the contextmenuevent provide anything useful for this purpose: it has no spell-check information and you cannot read the list of context menu items (which may contain spelling suggestions). The changeevent also doesn't provide spell-check information.

不,该contextmenu事件也没有为此提供任何有用的信息:它没有拼写检查信息,您无法阅读上下文菜单项列表(其中可能包含拼写建议)。该change事件也不提供拼写检查信息。

How does one detect a spelling mistake inside a textarea in JavaScript?

如何检测 JavaScript 文本区域内的拼写错误?

You can either code this yourself or use a third party library. There are other Stack Overflow questions on this topic or you can search for yourself. Related Stack Overflow questions include:

您可以自己编写代码或使用第三方库。关于此主题还有其他 Stack Overflow 问题,或者您可以自行搜索。相关的堆栈溢出问题包括:

回答by GitaarLAB

As the question seems a bit broad and open to interpretation (especially with the current bounty-'requirements'), I'll start by explaining how I interpret it and try to answer the subquestions in the process (Q/A style).

由于这个问题似乎有点宽泛且易于解释(特别是对于当前的赏金-“要求”),我将首先解释我如何解释它并尝试回答过程中的子问题(Q/A 风格)。

You seem to be asking:

你似乎在问:

"Google Chrome"/"Chromium" specific:

“谷歌浏览器”/“铬”特定:

  1. Q:if browser "Google Chrome"/"Chromium" exposes a spellcheck-APIthat you can interact with through the use of javascriptin a common webpage
    A:No, not really (at least not in the way you'd want).
    There is a Chromium-specific Spellcheck API Proposal(from dec 2012).

    Here are some parts of it:

    Could this API be part of the web platform?
    It is unlikely that spellchecking will become part of the web platform.

    More importantly, it has only one method called 'loadDictionary':

    loadDictionary( myDictionaryFile // string path or URL
                  , dictionaryFormat // enumerated string [ "hunspell" (concatentation of .aff and .dic files)
                                     //                   , "text"     (plain text)
                                     //                   ]
                  ) // returns int indicating success or an error code in loading the dictionary.      
    

    The point? Helping the community create custom dictionaries for Zulu, Klingon, etc. because approximately 20-30% of Spellcheck bugs-rapports were regarding unsupported languages.

    Now let's not confuse Chrome's SpellCheck API(above) with Chrome/Webkit's SpellCheck API(hu? say what?):
    Hironori Bono (a software engineer for Google Chrome) proposed an APIaround 2011 and some related bug rapportsand a patchthat was(/is still?) in Chrome.

    void addSpellcheckRange( unsigned long start
                           , unsigned long length
                           , DOMStringList suggestions
                       // [, unsigned short options]
                           );
    void removeSpellcheckRange(SpellcheckRange range);
    

    Usage example:

    var input = document.querySelector('input');
    input.addSpellcheckRange( 4
                            , 9
                            , [ 'Chrome'
                              , 'Firefox'
                              , 'Opera'
                              , 'Internet Explorer'
                              ]
                            );
    

    from http://peter.sh/experiments/spellcheck-api/
    Sources:
    http://html5-demos.appspot.com/static/html5-whats-new/template/index.html#42,
    http://peter.sh/experiments/spellcheck-api/(you should be able to try it live there IF this API still works..)

    The point? After contemplating over this a couple of day's it suddenly clicked: custom spell-check integration with the browser - using the browser's context-menu instead of blocking it and providing your own. So one could link that with an existing external spell-check library.

    Above historical and experimental API's clearly never directly supported what you want to accomplish.

  2. Q:if "Google Chrome"/"Chromium" spellcheck-API exposes an 'onSpellError' (-like) eventon (for example) a textarea
    A:As outlined above, it appears that Chrome doesn't have such an event.
    HTM5 currently only exposes the ability to enable or disable spell-checking on spellcheck supported elements.
  3. Q:how to access Chrome's spell-check suggestions for a misspelled word
    A:As outlined above: it appears that you can't. It appears to be the same answer as for the almost duplicate-question: How can I access Chrome's spell-check dictionary?
    It might be interesting to note that "TinyMCE's spellchecker was previously provided by 'hacking' a Chrome toolbar API owned by Google, against Google's own legal usage policies. This spellchecking service has been discontinued permanently.". Now if you search the web you probably can find how they did that, but it certainly doesn't seem the best way to go about it (and advocate it here).
    Using javascript spell-check libraries you could however use Chrome's dictionaries (so you wouldn't need to maintain the dictionaries) but you would have to supply and ship these files together with your web-app (instead of fetching the installed ones in the browser).
  1. 问:如果浏览器“Google Chrome”/“Chromium”公开了一个拼写检查 API,您可以通过普通网页中使用 javascript与之交互
    A:不,不是真的(至少不是您想要的方式)。
    有一个特定于 Chromium 的Spellcheck API提案(从 2012 年 12 月开始)。

    以下是其中的一些部分:

    这个 API 可以成为网络平台的一部分吗?
    拼写检查不太可能成为网络平台的一部分。

    更重要的是,它只有一种名为“loadDictionary”的方法:

    loadDictionary( myDictionaryFile // string path or URL
                  , dictionaryFormat // enumerated string [ "hunspell" (concatentation of .aff and .dic files)
                                     //                   , "text"     (plain text)
                                     //                   ]
                  ) // returns int indicating success or an error code in loading the dictionary.      
    

    重点?帮助社区为祖鲁语、克林贡语等创建自定义词典,因为大约 20-30% 的拼写检查错误报告与不受支持的语言有关。

    现在,让我们不要将 Chrome 的SpellCheck API(上图)与 Chrome/Webkit 的SpellCheck API(哈?说什么?)混淆:
    Hironori Bono(谷歌 Chrome 的软件工程师)在 2011 年左右提出了一个 API和一些相关的错误报告和一个补丁( / 仍然?)在 Chrome 中。

    void addSpellcheckRange( unsigned long start
                           , unsigned long length
                           , DOMStringList suggestions
                       // [, unsigned short options]
                           );
    void removeSpellcheckRange(SpellcheckRange range);
    

    用法示例:

    var input = document.querySelector('input');
    input.addSpellcheckRange( 4
                            , 9
                            , [ 'Chrome'
                              , 'Firefox'
                              , 'Opera'
                              , 'Internet Explorer'
                              ]
                            );
    

    来自 http://peter.sh/experiments/spellcheck-api/
    来源:
    http://html5-demos.appspot.com/static/html5-whats-new/template/index.html#42
    http://peter.sh/experiments/spellcheck-api/(你应该能够如果此 API 仍然有效,请在那里尝试。)

    重点是什么?在考虑了几天之后,它突然点击了:与浏览器的自定义拼写检查集成 - 使用浏览器的上下文菜单而不是阻止它并提供您自己的。因此,可以将其与现有的外部拼写检查库联系起来。

    上面的历史和实验 API 显然从来没有直接支持你想要完成的事情。

  2. 问:如果“Google Chrome”/“Chromium”拼写检查 API在(例如)文本区域上公开了“onSpellError”(类似)事件
    A:如上所述,Chrome 似乎没有这样的事件。
    HTM5 目前仅公开启用或禁用拼写检查支持元素的拼写检查的能力。
  3. 问:如何访问 Chrome 对拼写错误的单词的拼写检查建议
    A:如上所述:您似乎不能。它似乎与几乎重复的问题的答案相同:如何访问 Chrome 的拼写检查字典?
    有趣的是,“ TinyMCE 的拼写检查器之前是通过‘黑客’谷歌拥有的 Chrome 工具栏 API 提供的,违反了谷歌自己的法律使用政策。此拼写检查服务已永久停止。”。现在,如果您搜索网络,您可能会找到他们是如何做到的,但这似乎不是最好的方法(并在此处提倡)。
    使用 javascript 拼写检查库,您可以使用 Chrome 的字典(因此您不需要维护字典),但您必须将这些文件与您的网络应用程序一起提供和发送(而不是在浏览器中获取已安装的文件) )。

General:

一般的:

  1. Q:How to detect a spelling mistake inside a textarea in JavaScript
    A:Internet Explorer allows using the spellchecker integrated into Microsoft Word via ActiveX as listed in the following code snippet.

    function CheckText(text) {
      var result = new Array;
      var app = new ActiveXObject('Word.Application');
      var doc = app.Documents.Add();
      doc.Content = text;
      for (var i = 1; i <= doc.SpellingErrors.Count; i++) {
        var spellingError = doc.SpellingErrors.Item(i);
        for (var j = 1; j <= spellingError.Words.Count; j++) {
          var word = spellingError.Words.Item(j);
          var error = {};
          error.word = word.Text;
          error.start = word.Start;
          error.length = word.Text.length;
          error.suggestions = new Array;
          var suggestions = word.GetSpellingSuggestions();
          for (var k = 1; k <= suggestions.Count; k++) {
            error.suggestions.push(suggestions.Item(k).Name);
          }
          result.push(error);
        }
      }
      return result;
    }
    

    Source: https://lists.w3.org/Archives/Public/public-webapps/2011AprJun/0516.html

    But IE/ActiveX/MS-Word isn't really what you have asked for, neither is it very cross platform/browser, that leaves us with local javascript spell-check libraries:
    Javascript Spell Checking Methods
    http://code.google.com/p/bjspell/
    http://www.javascriptspellcheck.com/
    http://ejohn.org/blog/revised-javascript-dictionary-search/
    Etc.
    Comparing/explaining them is really outside the scope of this answer.
    It is worth noting what format of dictionary you wish to use!

    Alternatively one could use an external spellcheck API service (where a server handles the data and you'd communicate with it using AJAX).
    Obviously you'd need to take privacy matters into account!

  1. 问:如何检测 JavaScript 文本区域内的拼写错误
    答:Internet Explorer 允许使用以下代码片段中列出的通过 ActiveX 集成到 Microsoft Word 中的拼写检查器。

    function CheckText(text) {
      var result = new Array;
      var app = new ActiveXObject('Word.Application');
      var doc = app.Documents.Add();
      doc.Content = text;
      for (var i = 1; i <= doc.SpellingErrors.Count; i++) {
        var spellingError = doc.SpellingErrors.Item(i);
        for (var j = 1; j <= spellingError.Words.Count; j++) {
          var word = spellingError.Words.Item(j);
          var error = {};
          error.word = word.Text;
          error.start = word.Start;
          error.length = word.Text.length;
          error.suggestions = new Array;
          var suggestions = word.GetSpellingSuggestions();
          for (var k = 1; k <= suggestions.Count; k++) {
            error.suggestions.push(suggestions.Item(k).Name);
          }
          result.push(error);
        }
      }
      return result;
    }
    

    来源:https: //lists.w3.org/Archives/Public/public-webapps/2011AprJun/0516.html

    但是 IE/ActiveX/MS-Word 并不是您真正想要的,也不是跨平台/浏览器,这让我们只能使用本地 javascript 拼写检查库
    Javascript 拼写检查方法
    http://code.google。 com/p/bjspell/
    http://www.javascriptspellcheck.com/
    http://ejohn.org/blog/revised-javascript-dictionary-search/
    等等。
    比较/解释它们确实超出了这个答案的范围。
    值得注意的是您希望使用什么格式的字典!

    或者,可以使用外部拼写检查 API 服务(服务器处理数据,您可以使用 AJAX 与之通信)。
    显然,您需要考虑隐私问题!

The bounty-'requirements' ask for:

赏金-“要求”要求:

  1. Q:definitive proof
    A:I should have found something more regarding the subject than some esoteric experimental features. Neither do I see libraries that try to shim their functionality into some (upcoming) standardized method/event identifiers etc.
    As noted, popular libraries like TinyMCE also currently have no other solution.
    In the 'living standard'/'the world is our playground' mentality my answer could very well already be outdated when I press the 'submit'-button. But even then I wouldn't recommend such an experimental feature in the near future on a 'production' level website/interface.
  2. Q:and obtaining a good answer explaining how to achieve this
    (chrome specific or in general? Spell-check suggestions or detecting that there is a typo?)
    A:Other than the above, I can't think of anything (other than libraries that web-developers currently use (see 4)).
  1. 问:确凿的证据
    A:我应该找到更多关于这个主题的东西,而不是一些深奥的实验特征。我也没有看到试图将其功能填充到某些(即将到来的)标准化方法/事件标识符等中的
    库。如前所述,像 TinyMCE 这样的流行库目前也没有其他解决方案。
    在“生活标准”/“世界就是我们的游乐场”的心态下,当我按下“提交”按钮时,我的答案很可能已经过时了。但即便如此,我也不会在不久的将来在“生产”级别的网站/界面上推荐这样的实验性功能。
  2. 问:并获得一个很好的答案来解释如何实现这一点
    (特定于 Chrome 或一般?拼写检查建议或检测到有错字?)
    A:除上述之外,我想不出任何东西(除了库网络开发者目前使用的(见 4))。

Hope this helps!

希望这可以帮助!

回答by aecend

There is not an API for accessing Chrome's spellcheck suggestions, nor are there natively any events fired when words are mistyped. However, events couldbe implemented.

没有用于访问 Chrome 的拼写检查建议的 API,也没有在单词输入错误时触发的任何事件。但是,可以实施事件。

I have no idea what your use-case is for this functionality, but I put together a demonstration using montanaflynn's Spellcheck API on MashApe. The demo watches a text area, and when the user pauses typing, it sends the text via the API to be tested. The API returns JSON containing the original string, the suggested corrected string, and an object containing the corrected words and their suggested replacements.

我不知道您使用此功能的用例是什么,但我在 MashApe 上使用montanaflynn 的 Spellcheck API 进行了演示。该演示观察一个文本区域,当用户暂停输入时,它会通过 API 发送文本进行测试。API 返回包含原始字符串、建议的更正字符串以及包含更正单词及其建议替换的对象的 JSON。

The suggestions are displayed below the textarea. When suggestions are hovered, the mistyped word is highlighted. When clicked, the typo is replaced with the suggestion.

建议显示在文本区域下方。当建议悬停时,错误输入的词会突出显示。单击后,拼写错误将替换为建议。

I also added a shuffling function, that scrambles the words in the string before sending it, to add a layer of privacy to the use of the API (it uses SSL also). Neither the API nor Chrome use context-based suggestions, so the shuffling doesn't alter the results.

我还添加了一个改组功能,在发送之前对字符串中的单词进行打乱,为 API 的使用添加一层隐私(它也使用 SSL)。API 和 Chrome 都不使用基于上下文的建议,因此改组不会改变结果。

Here's a link to the CodePen: http://codepen.io/aecend/pen/rOebQq

这是 CodePen 的链接:http://codepen.io/aecend/pen/rOebQq

And here is the code:

这是代码:

CSS

CSS

<style>

    * {
        font-family: sans-serif;
    }

    textarea {
        margin-bottom: 10px;
        width: 500px; 
        height: 300px;
        padding: 10px;
    }

    .words {
        width: 500px;
    }

    .word {
        display: inline-block;
        padding: 2px 5px 1px 5px;
        border-radius: 2px;
        background: #00B1E6;
        color: white;
        margin: 2px;
        cursor: pointer;
    }

</style>

HTML

HTML

<textarea id="text" placeholder="Type something here..."></textarea>
<div id="words"></div>

JavaScript

JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script>

    ;(function(){

        "use strict";

        var words = document.getElementById("words"),
            input = document.getElementById("text"),
            timeout, xhr;

        input.addEventListener("keyup", function(e){

            if (timeout) clearTimeout(timeout);

            if (!this.value.trim()) words.innerHTML = '';

            timeout = setTimeout(function() {

                var test_phrase = shuffle_words( input.value );

                spell_check(test_phrase);

                timeout = null;

            }, 500);

        });

        function shuffle_words(inp) {

            inp = inp.replace(/\s+/g, ' ');

            var arr = inp.split(" "),
                n = arr.length;

            while (n > 0) {
                var i = Math.floor(Math.random() * n--),
                    t = arr[n];
                arr[n] = arr[i];
                arr[i] = t;
            }

            return arr.join(' ');
        }

        function spell_check(text){

            if (xhr) xhr.abort();

            xhr = $.ajax({
                url: 'https://montanaflynn-spellcheck.p.mashape.com/check/',
                headers: {
                    'X-Mashape-Key': 'U3ogA8RAAMmshGOJkNxkTBbuYYRTp1gMAuGjsniThZuaoKIyaj',
                    'Accept': 'application/json'
                },
                data: { 
                    'text': text
                },
                cache: false,
                success: function(result){

                    xhr = null;
                    suggest_words(result);

                }
            });

        }

        function suggest_words(obj){

            if (!obj.corrections) return;

            words.innerHTML = '';

            for (var key in obj.corrections) {

                if (obj.corrections.hasOwnProperty(key)) {

                    var div = document.createElement("div");
                    div.className = "word";
                    div.innerHTML = obj.corrections[key][0];
                    div.orig = key;

                    div.onmouseover = function() {
                        var start = input.value.indexOf(this.orig);
                        input.selectionStart = start;
                        input.selectionEnd = start + this.orig.length;
                    };

                    div.onmouseout = function() {
                        var len = input.value.length;
                        input.selectionStart = len;
                        input.selectionEnd = len;
                    }

                    div.onclick = function() {
                        input.value = input.value.replace(this.orig, this.innerHTML);
                        this.parentNode.removeChild(this);
                    }

                    words.appendChild(div);

                }

            }

        }

    })();

</script>

I only used jQuery to simplify the AJAX request for this demonstration. This could easily be done in vanilla JS.

我只使用 jQuery 来简化这个演示的 AJAX 请求。这可以在 vanilla JS 中轻松完成。

回答by Eugene Tiurin

You can disable internal browser spellcheck and integrate any other opensource spellcheck library, for example JavaScript SpellCheck. It contains all events you may need for deep integration, check the API page.

您可以禁用内部浏览器拼写检查并集成任何其他开源拼写检查库,例如 JavaScript SpellCheck。它包含深度集成可能需要的所有事件,请查看API 页面