简体   繁体   中英

How can I output HTML from a Google Apps Script?

I have this simple script to get a page and output it unchanged. However, the browser doesn't recognize the output as HTML and shows it as text.

function doGet(e) {
  var url = e.queryString || "";
  if (url != "") {
    return getPage(url);
  }  
  return "not found";
}

function test() {
  return getPage("www.google.com");
}

function getPage(url) {
  var options = {
    headers : {'Cache-Control' : 'max-age=0'}
  };
  var response = UrlFetchApp.fetch(url, options);
  var html = response.getContent();
  return ContentService.createTextOutput(html).setMimeType(ContentService.MimeType.HTML);
}

What's wrong? How can I output the fetched page as HTML?

Use this return in your getPage() function instead:

var html = response.getContentText();
return HtmlService.createHtmlOutput(html);

However, do not expect the fetched page to be "unchanged" - HTML Service will sanitize the content, which may result in some page functionality being removed or not working.

Also keep in mind that your web app is rendered inside an iframe - your fetched page may not allow it to be run in an iframe or employ a frame-breakout javascript which may result in your users being redirected away from your web app to the actual url of the fetched page.

I must ask, though: are you certain you must render the external page this way? Wouldn't a simple <a href="..." target="_blank">link to external page (will open in a new tab/window)</a> suffice?

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