3

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?

2

1 Answer 1

6

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?

Sign up to request clarification or add additional context in comments.

2 Comments

"Wouldn't a simple..." This is to fetch a page that may be blocked. I changed the return to use your suggestion, but now all I get is a variable length string of comma separated integers for each page fetched. Here's a small sample of what appears to be ASCII values when fetching stackoverflow.com: 60,33,68,79,67,84,89,80,69,32,104,116,109,108,62,13,10,60,104,116,109,108,62,13,10,60,104,101,97,100,62,13,10,32,32,32,32,13,10,32,32,32,32,60,116,105,116,108,101,62,83,116,97,99,107,32,79,118,101,114,102,108,111,119,60,47,116,105,116,108,101,62,13,10,32,32,32,32,60,108,105,110,107,32,114
Sorry, it should be .getContentText() instead of .getContent(). I have edited the code in my answer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.