google-apps-scriptgoogle-docs

How to get the bookmark link?


I would like to get the bookmark link after I run addBookmark() on Google Docs. I see that we cannot use the getUrl() for the bookmark. I'm thinking of using the id of bookmark but I am having trouble on the url.

My current code to get the bookmark link looks like this.

doc = DocumentApp.getActiveDocument();
bookmark = doc.addBookmark(position);
let bookmarklink = String(doc.getUrl() + '/edit#bookmark=' + boomark.getId());

Is there any other implementation that is more dynamic? I would like for it to work on test (test deploy), my problem is that I get a different url from doc.getUrl() on test.


Solution

  • It seems that DocumentApp.getActiveDocument().getUrl() returns the URL like https://docs.google.com/open?id={fileId}. On the other hand, the hyperlink of bookmark is like https://docs.google.com/document/d/{fileId}/edit#bookmark=id.{bookmarkId}. I thought that this might be the reason for your current issue. If you want to retrieve the bookmark URL, how about the following modification?

    From:

    let bookmarklink = String(doc.getUrl() + '/edit#bookmark=' + boomark.getId());
    

    To:

    let bookmarklink = DriveApp.getFileById(doc.getId()).getUrl().replace("?usp=drivesdk", "#bookmark=" + bookmark.getId());
    

    or

    let bookmarklink = `https://docs.google.com/document/d/${doc.getId()}/edit#bookmark=${bookmark.getId()}`;