x-x
x-x

Reputation: 7515

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?

Upvotes: 3

Views: 8634

Answers (1)

azawaza
azawaza

Reputation: 3084

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?

Upvotes: 6

Related Questions