W3cubDocs

/DOM

Body.text

The text() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text). The response is always decoded using UTF-8.

Syntax

response.text().then(function (text) {
  // do something with the text response 
});

Parameters

None.

Returns

A promise that resolves with a USVString.

Example

In our fetch text example (run fetch text live), we have an <article> element and three links (stored in the myLinks array.) First, we loop through all of these and give each one an onclick event handler so that the getData() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked.

When getData() is run, we create a new request using the Request() constructor, then use it to fetch a specific .txt file. When the fetch is successful, we read a USVString (text) object out of the response using text(), then set the innerHTML of the <article> element equal to the text object.

var myArticle = document.querySelector('article');
var myLinks = document.querySelectorAll('ul a');

for(i = 0; i <= myLinks.length-1; i++) {
  myLinks[i].onclick = function(e) {
    e.preventDefault();
    var linkData = e.target.getAttribute('data-page');
    getData(linkData);
  }
};
    
function getData(pageId) {
  console.log(pageId);
  var myRequest = new Request(pageId + '.txt');
  fetch(myRequest).then(function(response) {
    return response.text().then(function(text) {
      myArticle.innerHTML = text;
    });
  });
}

Specifications

Specification Status Comment
Fetch
The definition of 'text()' in that specification.
Living Standard

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support 42
42
41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Yes 39
39
34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enabled preference. To change preferences in Firefox, visit about:config.
No 29
29
28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
No
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support No No Yes No No No No

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Body/text