buzzlyhan
buzzlyhan

Reputation: 15

How to write a script to enable links in Google Docs (google apps)?

Can anyone help me to answer my question?
I can write a link to Google docs with a script, but I don't know how to link that URL.
I want to enable to link "tmpURL" in the following example.

  var rowsData =  [
                    ['titleA', 'URL'], 
                    ['AAA', tmpURL]
                  ];

  table = body.appendTable(rowsData);
  table.getRow(0).editAsText().setBold(true);

Thanks.

Upvotes: 1

Views: 157

Answers (1)

Tanaike
Tanaike

Reputation: 201388

I believe your goal as follows.

  • You want to append a table and you want to set the hyperlink to the column "B" of the table. The URL is the same with the text in the cell.
  • You want to achieve this using Google Apps Script.

In this case, how about the following modification?

Modified script:

var body = DocumentApp.getActiveDocument().getBody();
var tmpURL  = "###"; // Please set the URL.

var rowsData = [
  ['titleA', 'URL'],
  ['AAA', tmpURL],
];
table = body.appendTable(rowsData);
table.getRow(0).editAsText().setBold(true);
var text = table.getCell(1, 1).editAsText();
text.setLinkUrl(text.getText());
  • In this modification, the column "B" of the row 2 has the hyperlink.

  • When you want to reflect the hyperlink of the column "B", you can also the following script. In this script, even when the number of rows is more than 2, the column "B" has the hyperlink.

      var body = DocumentApp.getActiveDocument().getBody();
      var tmpURL  = "###"; // Please set the URL.
    
      var rowsData = [
        ['titleA', 'URL'],
        ['AAA', tmpURL],
      ];
      table = body.appendTable(rowsData);
      table.getRow(0).editAsText().setBold(true);
      var rows = table.getNumRows();
      for (var r = 1; r < rows; r++) {
        var text = table.getCell(r, 1).editAsText();
        text.setLinkUrl(text.getText());
      }
    

References:

Upvotes: 2

Related Questions