How to add a hyperlink in a Google Docs using a Google Script
To add a hyperlink in a document use Body.appendParagraph with setLinkUrl, then merge.
let doc = DocumentApp.create("My Document");
let body = doc.getBody();
body.appendParagraph("Please click ");
let link = body.appendParagraph("here").setLinkUrl("http://www.google.com");
link.merge();
let closing = body.appendParagraph(".");
closing.merge();
The code above will create a document with text that looks like:
Please click here.
You should be able to use setFormula and the Hyperlink formula like so:
var value = '=HYPERLINK("www.google.com", "Google")';
SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Sheet1")
.getRange("A1")
.setFormula(value);
Edit: Looks like I misread the question. Try this instead:
DocumentApp.getActiveDocument()
.getBody()
.editAsText()
.insertText(0, "link text")
.setLinkUrl("www.google.com");
Edit 2: Looks like .setLinkUrl()
is effecting the whole body, not the text inserted. If you put the link text into a variable and use the length of the variable to mark the link area, it should work. Try this instead:
function insertLink() {
var text = "link text\n";
var url = "www.google.com";
DocumentApp.getActiveDocument()
.getBody()
.editAsText()
.insertText(0, text)
.setLinkUrl(0, text.length, url);
}