Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a hyperlink in a Google Docs using a Google Script

I have always used the insertText() function, but now I want to write a link in my google docs. The ideal would be to be able to write in HTML, but I don't know how.. it seems that it is not possible with the insertText() function.

How can I do that ?

like image 988
qcha Avatar asked Sep 16 '15 07:09

qcha


People also ask

How do you hyperlink in Google script?

To create a link, select the text that you want to be the link, and then click on the HYPERLINK icon in the toolbar. In the "Link to" field, enter the web address or the name of the sheet that you want to link to. Then, click on the "Create" button.


1 Answers

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);
}
like image 60
SBmore Avatar answered Sep 21 '22 08:09

SBmore