[javascript] How to dynamically change a web page's title?

I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side.

Now there is a requirement to change the page title according to the tab selected on the page ( for SEO reasons ). Is this possible? Can someone suggest a solution to dynamically alter the page title via javascript without reloading the page?

This question is related to javascript html

The answer is


The code is
document.title = 'test'


I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.

Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.


You can use JavaScript. Some bots, including Google, will execute the JavaScript for the benefit of SEO (showing the correct title in the SERP).

document.title = "Google will run this JS and show the title in the search results!";

However, this is more complex since you are showing and hiding tabs without refreshing the page or changing the URL. Maybe adding an anchor will help as stated by others. I may need to retract my answer.

Articles showing positive results: http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/ http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry

Don't always assume a bot won't execute JavaScript. http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 Google and other search engines know that the best results to index are the results that the actual end user will see in their browser, including JavaScript.


One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.


Google mentioned that all js files rendered but in real, I've lost my title and another meta tags which had been provided by Reactjs on this website and actually lost my position on Google! I've searched a lot but it seems that all pages must have pre-rendered or using SSR(Server Side Rendering) to have their SEO-friendly protocole!
It expands to Reactjs, Angularjs , etc.
For short, Every page that has view page source on browser is indexed by all robots, if it's not probably Google can index but others skip indexing!


But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes


Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.


Modern crawlers are able to parse dynamically-generated content in the DOM, so using document.title = ... is perfectly fine.


Use document.title. It will be useful for most things, but it will destroy SEO on your website.

Example:

_x000D_
_x000D_
document.write("title - " + document.title + "<br>");_x000D_
document.title = "New title here!";_x000D_
// Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites._x000D_
document.write("title - " + document.title + "<br>");
_x000D_
body {_x000D_
  font-family: Consolas, 'Courier New', monospace;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head><title>Old title</title></head>_x000D_
  <body><p>_x000D_
    Lorem ipsum dolor sit amet, at movet detraxit mediocritatem eam, nam iusto abhorreant ne. Ei pro          debet adolescens voluptaria, eu minim scaevola conceptam vel. Vim ea torquatos constituto                complectitur, usu eu civibus insolens eleifend. Ex ubique quaerendum his._x000D_
_x000D_
  </p></body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)


Modern crawlers are able to parse dynamically-generated content in the DOM, so using document.title = ... is perfectly fine.


You'll have to re-serve the page with a new title in order for any crawlers to notice the change. Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.


You can use JavaScript. Some bots, including Google, will execute the JavaScript for the benefit of SEO (showing the correct title in the SERP).

document.title = "Google will run this JS and show the title in the search results!";

However, this is more complex since you are showing and hiding tabs without refreshing the page or changing the URL. Maybe adding an anchor will help as stated by others. I may need to retract my answer.

Articles showing positive results: http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/ http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry

Don't always assume a bot won't execute JavaScript. http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 Google and other search engines know that the best results to index are the results that the actual end user will see in their browser, including JavaScript.


But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes


The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)


I want to say hello from the future :) Things that happened recently:

  1. Google now runs javascript that is on your website1
  2. People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google1
  3. you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that1

So to answer your question you can safely change title and other meta tags from javascript (you can also add something like https://prerender.io if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple:

if (document.title != newTitle) {
    document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);

Just make sure that css and javascript is not blocked in robots.txt, you can use Fetch as Google service in Google Webmaster Tools.

1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157


Since search engines ignore most javascript, you will need to make it so that search engines can crawl using the tabs without using Ajax. Make each tab a link with an href that loads the entire page with that tab selected. Then the page can have that title in the tag.

The onclick event handler can still load the pages via ajax for human viewers.

To see the pages as most search engines see them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title.

If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:

document.title = 'Put the new title here';

However, search engines will not see this change made in javascript.


I use a seperate header and include it using php, in the header i use:

<?php
if (!isset($title)){
    $title = "Your Title";
  }
  else {
    $title = $title;
  }
 ?>
<head>
<title><?php echo $title; ?></title>

Then in each page I use:

<?php
  $title = "Your Title - Page";
  include( "./header.php" );
?>

I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.

If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.


Use document.title.

See this page for a rudimentary tutorial as well.


But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes


I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.

If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.


Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.


The code is
document.title = 'test'


Since search engines ignore most javascript, you will need to make it so that search engines can crawl using the tabs without using Ajax. Make each tab a link with an href that loads the entire page with that tab selected. Then the page can have that title in the tag.

The onclick event handler can still load the pages via ajax for human viewers.

To see the pages as most search engines see them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title.

If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:

document.title = 'Put the new title here';

However, search engines will not see this change made in javascript.


Use document.title.

See this page for a rudimentary tutorial as well.


for those looking of the npm version of it, there is an entire library for this:

npm install --save react-document-meta


import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (
      <div>
        <DocumentMeta {...meta} />
        <h1>Hello World!</h1>
      </div>
    );
  }
}

React.render(<Example />, document.getElementById('root'));

I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.

If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.


for those looking of the npm version of it, there is an entire library for this:

npm install --save react-document-meta


import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (
      <div>
        <DocumentMeta {...meta} />
        <h1>Hello World!</h1>
      </div>
    );
  }
}

React.render(<Example />, document.getElementById('root'));

Use document.title.

See this page for a rudimentary tutorial as well.


I want to say hello from the future :) Things that happened recently:

  1. Google now runs javascript that is on your website1
  2. People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google1
  3. you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that1

So to answer your question you can safely change title and other meta tags from javascript (you can also add something like https://prerender.io if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple:

if (document.title != newTitle) {
    document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);

Just make sure that css and javascript is not blocked in robots.txt, you can use Fetch as Google service in Google Webmaster Tools.

1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157


But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes


The code is
document.title = 'test'


I use a seperate header and include it using php, in the header i use:

<?php
if (!isset($title)){
    $title = "Your Title";
  }
  else {
    $title = $title;
  }
 ?>
<head>
<title><?php echo $title; ?></title>

Then in each page I use:

<?php
  $title = "Your Title - Page";
  include( "./header.php" );
?>

One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.


There are many ways you can change the title, the main two, are like so:

The Questionable Method

Put a title tag in the HTML (e.g. <title>Hello</title>), then in javascript:

let title_el = document.querySelector("title");

if(title_el)
    title_el.innerHTML = "World";

The Obviously Correct Method

The simplest of all is to actually use the method provided by the Document Object Model (DOM)

document.title = "Hello World";

The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ... in code they are maintaining.

What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.

Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior (here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole 'nother beast, so I digress.

Speaking of .innerHTML

Some good advice to keep in mind would be that using .innerHTML is generally sloppy. Use appendChild instead.

Although two cases where I still find .innerHTML to be useful include inserting plain text into a small element...

label.innerHTML = "Hello World";
// as opposed to... 
label.appendChild(document.createTextNode("Hello World"));
// example:
el.appendChild(function(){
    let el = document.createElement("span");
    el.className = "label";
    el.innerHTML = label_text;
    return el;
}());

...and clearing out a container...

container.innerHTML = "";
// as opposed to... umm... okay, I guess I'm rolling my own
[...container.childNodes].forEach(function(child){
    container.removeChild(child);
});

One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.


Use document.title.

See this page for a rudimentary tutorial as well.


You'll have to re-serve the page with a new title in order for any crawlers to notice the change. Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.


I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.

Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.


Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.


There are many ways you can change the title, the main two, are like so:

The Questionable Method

Put a title tag in the HTML (e.g. <title>Hello</title>), then in javascript:

let title_el = document.querySelector("title");

if(title_el)
    title_el.innerHTML = "World";

The Obviously Correct Method

The simplest of all is to actually use the method provided by the Document Object Model (DOM)

document.title = "Hello World";

The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ... in code they are maintaining.

What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.

Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior (here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole 'nother beast, so I digress.

Speaking of .innerHTML

Some good advice to keep in mind would be that using .innerHTML is generally sloppy. Use appendChild instead.

Although two cases where I still find .innerHTML to be useful include inserting plain text into a small element...

label.innerHTML = "Hello World";
// as opposed to... 
label.appendChild(document.createTextNode("Hello World"));
// example:
el.appendChild(function(){
    let el = document.createElement("span");
    el.className = "label";
    el.innerHTML = label_text;
    return el;
}());

...and clearing out a container...

container.innerHTML = "";
// as opposed to... umm... okay, I guess I'm rolling my own
[...container.childNodes].forEach(function(child){
    container.removeChild(child);
});

You'll have to re-serve the page with a new title in order for any crawlers to notice the change. Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.


Use document.title. It will be useful for most things, but it will destroy SEO on your website.

Example:

_x000D_
_x000D_
document.write("title - " + document.title + "<br>");_x000D_
document.title = "New title here!";_x000D_
// Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites._x000D_
document.write("title - " + document.title + "<br>");
_x000D_
body {_x000D_
  font-family: Consolas, 'Courier New', monospace;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head><title>Old title</title></head>_x000D_
  <body><p>_x000D_
    Lorem ipsum dolor sit amet, at movet detraxit mediocritatem eam, nam iusto abhorreant ne. Ei pro          debet adolescens voluptaria, eu minim scaevola conceptam vel. Vim ea torquatos constituto                complectitur, usu eu civibus insolens eleifend. Ex ubique quaerendum his._x000D_
_x000D_
  </p></body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.

If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.


One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.


The code is
document.title = 'test'


Maybe you can load on your title all the tabs titles in one string, and then once you load one of the tabs change the title via javascript

ex: at first set your title to

my app | description | contact | about us | 

once you load one of the tabs run:

document.title = "my app | tab title";

Google mentioned that all js files rendered but in real, I've lost my title and another meta tags which had been provided by Reactjs on this website and actually lost my position on Google! I've searched a lot but it seems that all pages must have pre-rendered or using SSR(Server Side Rendering) to have their SEO-friendly protocole!
It expands to Reactjs, Angularjs , etc.
For short, Every page that has view page source on browser is indexed by all robots, if it's not probably Google can index but others skip indexing!


Maybe you can load on your title all the tabs titles in one string, and then once you load one of the tabs change the title via javascript

ex: at first set your title to

my app | description | contact | about us | 

once you load one of the tabs run:

document.title = "my app | tab title";

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.