将换行符作为变量传递给 GAS 中的 insertText

Passing newline character as variable to insertText in GAS

我正在使用一个应用程序脚本边栏来插入文本,我输入的地方需要在开头附加一些文本,然后在再次输入后追加。

附加文本将由边栏中的文本框决定。

我将值作为 formObject

传递
function sendform(){
    var f = document.forms[0].elements;
    var data = {        "mytext": f[0].value }
    google.script.run.withSuccessHandler(ready).withFailureHandler(onFailure).processForm(data);
}

这是应用脚本代码。

    function processForm(fO)
    {
        var body = DocumentApp.getActiveDocument().getBody();
        body.editAsText().insertText(0, "\n\nsometext"); 
// this will perfectly insert the newlinenewlinesometext to the document

        body.editAsText().insertText(0, fO.mytext); 
// this will insert \n\nsometext which is wrong 
    }

我尝试使用 encodeURIComponent decodeURIComponent,但仍然是同样的问题。

有什么建议吗?

您可能需要先查看 Structure of a document 中给出的规则,您会在其中找到显示哪些文本元素可以插入以及哪些元素只能就地操作的树。

如前所述,Apps 脚本中的文档服务只能插入特定类型的元素。如果您在树中发现您正在尝试插入允许的元素,请参阅 Class Text to know the methods you can use on how to insert text such as insertText(offset, text)

插入文本的示例代码如下:

var body = DocumentApp.getActiveDocument().getBody();

 // Use editAsText to obtain a single text element containing
 // all the characters in the document.
 var text = body.editAsText();

 // Insert text at the beginning of the document.
 text.insertText(0, 'Inserted text.\n');

 // Insert text at the end of the document.
 text.appendText('\nAppended text.');

 // Make the first half of the document blue.
 text.setForegroundColor(0, text.getText().length / 2, '#00FFFF');