简体   繁体   中英

How to get a Google Web App to redirect to a specific cell in Sheets

MAIN GOAL :

  • Have an inventory system of QR Codes that, when scanned, directs to a Google Web App URL with a query string
  • This Web App searches a spreadsheet for the query string parameters and redirects to the cell that matches the parameter

Note that I can not simply use a URL linking to a cell. Rows are subject to be deleted as items sell. If a QR code directs to A3 and the item in A2 sells, then the item in A3 would become A2.

My problem is that I can't get the web app to redirect to the spreadsheet.

Here is my sheet & this is the code I'm using for the web app

function getCell(item, url){
  
  var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("Sheet1");
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange('A1:A' + lastRow).getValues();
  
  for(var i = 0; i < lastRow; i++){
    if(range[i] == item){
      return 'B' + (i + 1);
    }
  }
}

function doGet(e){
  var sheetUrl = "https://docs.google.com/spreadsheets/d/1K6xva3BRzxTAchXi1iseU0MiYCM4luN4edXCgmEv8MU/edit#gid=0";
  var cell = getCell(e.parameter.item, sheetUrl);

  return HtmlService.createHtmlOutput('<script>window.location.replace("' + sheetUrl + '&range=' + cell + '"</script>');
}

I'm trying this URL https://script.google.com/macros/s/AKfycbwdIZ8xbtf9iBHvNehcbJiYUE1E1gvDR7dyjPRM2CCGH1q_IwQ/exec?item=Dumbell_4 And it doesn't take me past the web app page.

Edit:

This works:

function doGet() {
  return HtmlService.createHtmlOutput('<script>window.top.location.replace("https://www.google.com")</script>');
}

Since the web app runs inside a subframe, we need to specify window.top before trying to use location.replace . (Thank you TheMaster for pointing this out.)

Original answer:

Apps Script web apps have restrictions that will prevent you from using window.location.replace to go to the URL of the Sheet.

I tried to see if HtmlService.setXFrameOptionsMode made any difference here, and it did not. Just received the error:

Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Any script you serve via HtmlService is going to be inside a frame and unable to redirect.

You can setup links that the user can click on, or display the sheet values in your web app and update them from the web app (you can emulate the Sheet in your own we app).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM