使用Chrome扩展程序替换TextArea中的文本 - JavaScript

时间:2017-08-09 02:35:51

标签: javascript html google-chrome

我试图用Google Chrome扩展程序中的字符串变量的内容替换TextArea中的文本。但由于某种原因,我的结果没有任何变化。这是我的代码:

内容脚本(js)

(function () {

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

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

        // 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) {

        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();

    }

    // Initialize ability to select and grab text from browser
    function lwsSetUpTextGetter(callback) {
        //Set the onmouseup function to lwsGetText
        document.onmouseup = lwsGetText;
        //Handling clicking outside webpage?
        if (!document.all) document.captureEvents(Event.MOUSEUP);


    }

    //Gets selected text
    function lwsGetText(e) {

        // 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
            // --Error here: does not set text at all--
            spanishText.innerHTML(lwsSelectedText);

        }

    }


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

        lwsAddContent(lwsActivateContent);

    });

})();

当我使用扩展程序时,弹出窗口加载,当我突出显示某些文本时,lwsSelectedText会填充正确的文本并显示在警报中,但它不会显示在我的文本区域中。我是否访问了lwsSpanishTextArea的内容错误?

谢谢!

1 个答案:

答案 0 :(得分:1)

要在输入中设置值,您可以使用属性value代替innerHTML

&#13;
&#13;
var lwsSelectedText = "Hello world!";
var spanishText = document.getElementById("spanishText");

spanishText.value = lwsSelectedText;
&#13;
<textarea id="spanishText"></textarea>
&#13;
&#13;
&#13;