Search code examples
google-apps-scriptgoogle-sheetscustom-function

Pushing a custom hyperlink to Google Sheets with Google Apps Script


I'm looking for an easy way to let my code turn a link from regular static text into a hyperlink that can be clicked. The code should let you put in an input of text, and then the code will automatically turn it into a link that lets you use that image search in the Google doodle game, Image Breakout, a spin-off of Atari Breakout.

The first thing I did was try this:

function IMAGEBREAKOUT(input) 
{
var array = [];
var url = 'https://www.google.com/search?q=' + input + '&tbm=isch&tbs=boee:1';
  array.push([url]);
  return array;
}

That only gave me regular text, and did not give me a clickable link, so then I tried this:

function IMAGEBREAKOUT(input) 
{
  var array = [];
  var url = 'https://www.google.com/search?q=' + input + '&tbm=isch&tbs=boee:1';
    array.push("<a href=url>" + url + "</a>");
    return array;
}

But, that only gave me static text with HTML formatting that didn't work. So, then I tried researching, and went on to try this:

function IMAGEBREAKOUT(input) 
{
 var array = [];
 var url = 'https://www.google.com/search?q=' + input + '&tbm=isch&tbs=boee:1';
    SpreadsheetApp.getActiveSheet().getActiveCell().setFormula('=HYPERLINK("' + url + )');
}

But it said I didn't have permission to call setFormula.

I tried authorizing the app later, and it worked when running it in the editor, but running the formula in Google Sheets gives me the same error.

I'm in a tight spot here. Can someone help me, or revise my script so that it doesn't require so much? If that's not possible, is there a simpler way to do this that I'm not thinking about? Thanks!


Solution

  • Thanks to @I'-'I, I was able to find out that I needed to encode the URI, so my code now looks like this:

    function IMAGEBREAKOUT(input) 
    {
      var url = 'https://www.google.com/search?q=' + input + '&tbm=isch&tbs=boee:1';
      return encodeURI([url]);
    }