How to dynamically change a web page's title?

JavascriptHtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Update: as per the comments and reference on SearchEngineLand most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

> You can just do something like, document.title = "This is the new > page title.";, but that would totally defeat the purpose of SEO. Most > crawlers aren't going to support javascript in the first place, so > they will take whatever is in the element as the page title. > > If you want this to be compatible with most of the important crawlers, > you're going to need to actually change the title tag itself, which > would involve reloading the page (PHP, or the like). You're not going > to be able to get around that, if you want to change the page title in > a way that a crawler can see.</p>

Solution 2 - Javascript

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

Solution 3 - Javascript

Use document.title.

See this page for a rudimentary tutorial as well.

Solution 4 - Javascript

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.

Solution 5 - Javascript

The code is
document.title = 'test'

Solution 6 - Javascript

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);
});

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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";

Solution 11 - Javascript

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'));

Solution 12 - Javascript

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

Example:

document.write("title - " + document.title + "<br>");
document.title = "New title here!";
// Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites.
document.write("title - " + document.title + "<br>");

body {
  font-family: Consolas, 'Courier New', monospace;
}

<!DOCTYPE html>
<html>
  <head><title>Old title</title></head>
  <body><p>
    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.

  </p></body>
</html>

Solution 13 - 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.

Solution 14 - Javascript

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.</p> <p>The onclick event handler can still load the pages via ajax for human viewers.</p> <p>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.</p> <p>If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:</p> <pre><code>document.title = 'Put the new title here'; </code></pre> <p>However, search engines will not see this change made in javascript.</p>

Solution 15 - Javascript

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.

Solution 16 - 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

Solution 17 - Javascript

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.

Solution 18 - Javascript

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!

Solution 19 - Javascript

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 :)

Solution 20 - 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" );
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser12129View Question on Stackoverflow
Solution 1 - JavascriptAlex FortView Answer on Stackoverflow
Solution 2 - JavascriptJLarkyView Answer on Stackoverflow
Solution 3 - Javascriptlc.View Answer on Stackoverflow
Solution 4 - JavascriptSaratView Answer on Stackoverflow
Solution 5 - JavascriptKevView Answer on Stackoverflow
Solution 6 - JavascriptBraden BestView Answer on Stackoverflow
Solution 7 - JavascriptTheTXIView Answer on Stackoverflow
Solution 8 - Javascriptdimitry_nView Answer on Stackoverflow
Solution 9 - JavascriptBryan DennyView Answer on Stackoverflow
Solution 10 - JavascriptSalvador VillegasView Answer on Stackoverflow
Solution 11 - Javascriptmel3kingsView Answer on Stackoverflow
Solution 12 - Javascriptgoblin01View Answer on Stackoverflow
Solution 13 - JavascriptRichView Answer on Stackoverflow
Solution 14 - Javascriptdougd_in_ncView Answer on Stackoverflow
Solution 15 - JavascriptyazzerView Answer on Stackoverflow
Solution 16 - JavascriptPbearneView Answer on Stackoverflow
Solution 17 - JavascriptshootingrubberView Answer on Stackoverflow
Solution 18 - JavascriptHamedView Answer on Stackoverflow
Solution 19 - JavascriptVanyo VanevView Answer on Stackoverflow
Solution 20 - JavascriptD. HenryView Answer on Stackoverflow