1

I would like to get the content of the <title> tag from any specified external page, using JavaScript. Specifically, this is using the Code app by Zapier (vanilla node.js v4.3.2), so additional libraries may not be supported.

fetch is supported...

fetch('http://example.com/')
  .then(function(res) {
    return res.text();
  })
  .then(function(body) {
    var output = {id: 1234, rawHTML: body};
    callback(null, output);
  })
  .catch(callback);

Docs state: "Very important - be sure to use callback in asynchronous examples!"

I am learning JavaScript and have been searching and trying various methods for hours. I don't fully understand the two functions in the example - I only need to return a "title", not the full body.

I was using an API designed to get page titles, but it seems to be a bit flaky. So I am hoping I can get titles using plain code.

3
  • What is the context? Is this supposed to run in a browser or on the server? Commented May 29, 2018 at 21:38
  • @FelixKling On the server, not browser. Commented May 29, 2018 at 21:45
  • This question is not a duplicate! It is specifically related to Zapier, which has specific limitations. Mod should read the question fully before marking as duplicate. Commented May 31, 2018 at 22:32

1 Answer 1

1

If you are using Node JS then you can use Request to get the page, then use Cheerio to parse its contents. To get the title you might do something like this:

const cheerio = require('cheerio');

request('http://example.com/', function (error, response, body) 
{
  if (error) {
      console.log(error);
      return
  }
  var $ = cheerio.load(body);
  var title = $("title").text();
});

If Cheerio is not available, you could do a more lowtech solution, and just use some simple splits. Not very robust, but might get you what you want.

fetch('http://example.com/')
  .then(function(res) {
    var body = res.text();
    var title = body.split('<title>')[1].split('</title>')[0]
  })
  .catch(callback);
Sign up to request clarification or add additional context in comments.

5 Comments

TypeError: body.split is not a function
Cheerio not available. Regular method produces the above error, which I take to refer to string definition. But I can't seem to successfully use toString() to fix, which is a solution I read about. Any ideas?
Got it working, I think - pastebin.com/BEyj0WSm
Your code looks functionally identical to mine. Strange!
what happens if the <title> tag has an attribute? for example: <title data-react-helmet="true">

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.