Apps Script - How can I get the selected text by the user in google doc?

358 views
Skip to first unread message

Zain Manna

unread,
May 22, 2023, 4:12:08 PM5/22/23
to Google Apps Script Community
I am trying to build a google doc add-on that capitalize the selected text by the user, but the first step i am trying to do is to log the selected text to the console. 
Can someone help in this? 

I wrote this in the client side (html):
$(document).ready(function() {
$('#selectionButton').click(function() {
var selectedText = window.getSelection().toString();
console.log("Selected Text:", selectedText);
});
});
And this in the server-side: 
function getSelection() {
var selection = DocumentApp.getActiveDocument().getSelection();
var selectedText = selection.getRangeElements()[0].getElement().asText().getText();
// Log the selected text to the console
console.log("Selected Text:", selectedText);
}
But I am getting nothing!

Brett Grear

unread,
May 23, 2023, 7:42:00 AM5/23/23
to Google Apps Script Community
What is the use case? This functionality exists in Google Docs already. SCR-20230523-hm3.png

However, you can do it server side. You wouldn't need any client side code if you make it a workspace add-on.  I don't think it would pass verification though seeing as it doesn't add anything new.

Zain Manna

unread,
May 23, 2023, 9:19:43 AM5/23/23
to Google Apps Script Community
and how can i access this function? 
I need to build a google add-ons that capitalize the selected text with keeping the formatting on a document, but I am not able to do this, because when the text is capitalized the formatting of the text is gone.   

Zain Manna

unread,
May 23, 2023, 9:20:13 AM5/23/23
to Google Apps Script Community
i mean the code of this functionality.  
Reply all
Reply to author
Forward
0 new messages