onMouseUp事件早期调用函数

时间:2017-08-10 06:55:27

标签: javascript google-chrome-extension

我有一个功能" snapSelectionToWord"应该在谷歌浏览器扩展程序中的onMouseUp事件上调用:

    // Initialize ability to select and grab text from browser
    function lwsSetUpTextGetter(callback) {

        console.log("lwsSetUpTextGetter()");

        //Set the onmouseup function to lwsGetText
        document.onmouseup = snapSelectionToWord(lwsGetText);
        //Handling clicking outside webpage?
        if (!document.all) document.captureEvents(Event.MOUSEUP);


    }

但是立即调用函数snapSelectionToWord而不是等待鼠标单击。我在这做错了什么。这是完整的代码......

内容脚本(js)

(function () {

    // Holds text being selected in browser
    var lwsSelectedText = '';

    // Adds pop-up to current webpage
    function lwsAddContent(callback) {

        console.log("lwsAddContent()");

        // Get body tag
        var body = document.getElementsByTagName('body');

        // add invisible div
        document.body.innerHTML += '<div id="myModal" class="modal"><div class="modal-content"><span class="close">&times;</span><div id="lwsSpanishDiv"><p id="lwsSpanishTitle">Spanish</p><textarea id="lwsSpanishTextArea">Hello</textarea></div><div id="lwsEnglishDiv"><p id="lwsEnglishTitle">English</p><textarea id="lwsEnglishTextArea">Hello 2</textarea></div></div></div>';

        callback(lwsSetUpTextGetter);

    }

    // Make the pop-up visible and set up close button
    function lwsActivateContent(callback) {

        console.log("lwsActivateContent()");

        var modal = document.getElementById('myModal');

        // Get the textarea
        var txtarea = document.getElementById("myTxtArea");

        // Get the <span> element that closes the modal
        var span = document.getElementsByClassName("close")[0];

        span.onclick = function () {
            modal.style.display = "none";
        }

        callback(quickTranslate);

    }

    // Initialize ability to select and grab text from browser
    function lwsSetUpTextGetter(callback) {

        console.log("lwsSetUpTextGetter()");

        //Set the onmouseup function to lwsGetText
        document.onmouseup = snapSelectionToWord(lwsGetText);
        //Handling clicking outside webpage?
        if (!document.all) document.captureEvents(Event.MOUSEUP);


    }

    // Snaps selected text to encompass the full word
    function snapSelectionToWord(callback) {

        console.log("snapSelectionToWord()");

        var sel;

        // Check for existence of window.getSelection() and that it has a
        // modify() method. IE 9 has both selection APIs but no modify() method.
        if (window.getSelection && (sel = window.getSelection()).modify) {
            sel = window.getSelection();
            if (!sel.isCollapsed) {

                // Detect if selection is backwards
                var range = document.createRange();
                range.setStart(sel.anchorNode, sel.anchorOffset);
                range.setEnd(sel.focusNode, sel.focusOffset);
                var backwards = range.collapsed;
                range.detach();

                // modify() works on the focus of the selection
                var endNode = sel.focusNode, endOffset = sel.focusOffset;
                sel.collapse(sel.anchorNode, sel.anchorOffset);
                if (backwards) {
                    sel.modify("move", "backward", "character");
                    sel.modify("move", "forward", "word");
                    sel.extend(endNode, endOffset);
                    sel.modify("extend", "forward", "character");
                    sel.modify("extend", "backward", "word");

                } else {
                    sel.modify("move", "forward", "character");
                    sel.modify("move", "backward", "word");
                    sel.extend(endNode, endOffset);
                    sel.modify("extend", "backward", "character");
                    sel.modify("extend", "forward", "word");
                }
            }
        } else if ((sel = document.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            if (textRange.text) {
                textRange.expand("word");
                // Move the end back to not include the word's trailing space(s),
                // if necessary
                while (/\s$/.test(textRange.text)) {
                    textRange.moveEnd("character", -1);
                }
                textRange.select();
            }
        }

        console.log("before callback...");

        callback(quickTranslate);

    }

    //Gets selected text
    function lwsGetText(callback) {
        return function (e) {

            console.log("lwsGetText()");

            // Get access to spanish text area
            var spanishText = document.getElementById('lwsSpanishTextArea');

            //Get text
            lwsSelectedText = (document.all) ? document.selection.createRange().text : document.getSelection();

            //if nothing is selected, do nothing
            if (lwsSelectedText != '') {

                // test: does browser grab text correctly?
                alert(lwsSelectedText);

                // Set spanish text area content to the selected text from browser
                spanishText.value = lwsSelectedText;

                // --Error Here--
                callback();

            }
        };
    }

    function quickTranslate() {

        console.log("quickTranslate()");

        var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
        keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";

        var englishTextArea = document.getElementById('lwsEnglishTextArea');
        var spanishTextArea = document.getElementById('lwsSpanishTextArea');

        englishTextArea.value = 'Working...';

        var xhr = new XMLHttpRequest(),
            textAPI = spanishTextArea.value,
            langAPI = 'es-en';
        data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                var res = this.responseText;
                var json = JSON.parse(res);
                if (json.code == 200) {
                    englishTextArea.value = json.text[0];
                }
                else {
                    englishTextArea.value = "Error Code: " + json.code;
                }
            }
        }

    }


    // When document ready
    $(document).ready(function () {

        lwsAddContent(lwsActivateContent);

    });

})();

控制台看起来像这样,如果我尝试点击并选择一些内容,则不会添加条目:

控制台日志

contentScript.js:9 lwsAddContent()
contentScript.js:24 lwsActivateContent()
contentScript.js:45 lwsSetUpTextGetter()
contentScript.js:58 snapSelectionToWord()
contentScript.js:106 before callback...

如果有人能弄清楚我在这里做错了什么,那就太好了!谢谢!

1 个答案:

答案 0 :(得分:-1)

document.onmouseup = snapSelectionToWord(lwsGetText);

更改为

document.onmouseup = snapSelectionToWord;

您应该分配功能,而不是功能调用。同样作为snapSelectionToWord中的第一个参数,您将收到event个对象。