简体   繁体   中英

Fetch API: Get title, keywords and body text from http response

I want to know what could be the best way to get the title, keywords and content visible to the user from responseText using fetch api ( Is there a way to not send cookies when making an XMLHttpRequest on the same origin? )

At the moment, I use regular expressions to get the title from the response text, for example:

var re_title = new RegExp("<title>[\n\r\s]*(.*)[\n\r\s]*</title>", "gmi");
var title = re_title.exec(responseText);
if (title)
    title = title[1]

And to get the content in the keyword meta tag, i need to employ several regular expressions.

To get the content visible to the user, we don't need tags like script, div etc. also, we don't need the text between script tags. This is to get only the words which are meaningful in the body of the response.

I think (also as per various stackoverflow post) using regular expressions for this is just not the right approach. What could be the alternative?

As zzzzBov mentioned, you can use your browser's implementation of the DOMParser API to achieve this by parsing the response.text() of a fetch request. Here's an example that sends such a request for itself and parses the title, keywords, and body text:

 <!DOCTYPE html> <html> <head> <title>This is the page title</title> <meta charset="UTF-8"> <meta name="description" content="Free Web Help"> <meta name="keywords" content="HTML,CSS,XML,JavaScript"> <meta charset="utf-8"> <script> fetch("https://dl.dropboxusercontent.com/u/76726218/so.html") .then(function(response) { return (response.text()); }) .then(function(responseText) { var parsedResponse = (new window.DOMParser()).parseFromString(responseText, "text/html"); document.getElementById("title").innerHTML = "Title: " + parsedResponse.title; document.getElementById("keywords").innerHTML = "Keywords: " + parsedResponse.getElementsByName("keywords")[0].getAttribute("content"); document.getElementById("visibleText").innerHTML = "Visible Text: " + parsedResponse.getElementsByTagName("body")[0].textContent; }); </script> </head> <body> <div>This text is visible to the user.</div> <div>So <i>is</i> <b>this</b>.</div> <hr> <b>Results:</b> <ul id="results"> <li id="title"></li> <li id="keywords"></li> <li id="visibleText"></li> </ul> </body> </html> 

I found Mozilla's documentation on the Fetch API , Using Fetch , and Fetch basic concepts helpful.

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