566

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?

Paolo Forgia
  • 5,804
  • 7
  • 39
  • 55
user12129
  • 5,691
  • 2
  • 15
  • 5

20 Answers20

778

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.

Darryl Hein
  • 134,677
  • 87
  • 206
  • 257
Alex Fort
  • 17,293
  • 5
  • 40
  • 51
  • 32
    If you're using html5's pushState to change history when updating your page already, why not update the title aswell. If set up properly crawlers would still get the right results and you'll still want the user to see the title matching the view he's on. For most web-apps etc. it seems like a good sollution to keep using this. I might have overlooked a different function though? – Mathijs Segers Aug 07 '13 at 08:55
  • 2
    Unfortunately browsers currently ignore the 'title' argument in pushState() and replaceState() [stackOverflow](http://stackoverflow.com/questions/13955520/page-title-is-not-changed-by-history-pushstate) [twiter blog](https://blog.twitter.com/2012/implementing-pushstate-for-twittercom) – mattsahr Nov 15 '13 at 16:53
  • 1
    The crawler will follow links though (or a sitemap), so if you can fully load the page with the new URL as well as get to that state through javascript, then as far as the crawler is concerned all of the titles will be valid – Nick Cooper Jun 09 '14 at 12:25
  • Actually it wouldn't defeat the purpose of SEO depending on how your application is serving content to google. You can actually redirect google to a headless browser, serving up html after your page is loaded. Each tab would need it's own hashbang or url, see googles own content on making ajax applications crawlable https://developers.google.com/webmasters/ajax-crawling/ – codewizard Oct 29 '14 at 17:09
  • 35
    This isn't quite true. Google does index javascript changes to document.title. See http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 – CpnCrunch Oct 29 '15 at 01:11
  • 8
    @CpnCrunch is correct! Google will index the title that was changed by JavaScript. I haven't tested on other search bots.Don't always assume a bot doesn't execute JavaScript. I created a new answer below, and then realized that simply showing and hiding tabs without changing the URL makes this more complex. – yazzer Nov 25 '15 at 21:24
  • 10
    @CpnCrunch is correct. This is 2016. SEO has changed a lot and Google and other search engines are adapting to single page apps and javascript in general. – pilau Jan 05 '16 at 17:50
  • 42
    So it means this answer is quite obsolete. StackOverflow should now add "Obsolete" feature for answers :D – Allen Linatoc Mar 14 '16 at 07:42
  • 3
    Just found that if the document is empty, e.g. `document.write('')`, then `document.title = 'foo'` will not work because the document does not contain a title element. In the case above, this worked for me: `document.write('zymbit')` – berto Mar 29 '16 at 19:02
  • 1
    The original question may have been posed for SEO reasons, but I had other reasons to need to update the title tag dynamically, and this was the first result and it quickly answered the question. Leaving title tags the same when the appropriate information in a database has changed, or when the user has navigated to a new page can offer a poor user experience. So there are reasons people might want to do this besides SEO. – cazort Jul 25 '17 at 14:35
  • Another use case is to show the progress of something, like an upload, or a task. – Sandwich Aug 17 '17 at 17:29
  • Nice idea @AllenLinatoc :) You can see this question: https://meta.stackoverflow.com/questions/272651/introduce-an-obsolete-answer-vote – simhumileco Jun 06 '19 at 16:31
  • I want to achieve the same effect but title appears on both the document and the web page. I want it to appear only on web page. – 7guyo Feb 15 '20 at 09:01
186

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

georgeawg
  • 46,994
  • 13
  • 63
  • 85
JLarky
  • 8,139
  • 3
  • 28
  • 24
  • Hello to the future! Wanted to ask why are you still using jQuery there and what for this comparison needed (`document.title != newTitle`) – Volodymyr I. Dec 04 '20 at 17:31
  • 1
    it was the future in 2016 mind you :) comparison is there just in the case if the title didn't change when navigating between pages, I guess description could have stayed the same, but it was just intended as short demostration – JLarky Dec 05 '20 at 05:56
47

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.

Sarat
  • 1,538
  • 11
  • 10
  • 3
    agreed - this won't help SEO at all, as the crawlers won't do anything with your JS – annakata Jan 05 '09 at 15:32
  • Maybe they just want one title but all the content on the SE, but then a more friendly organization of data once you're on the page? – Kev Jan 05 '09 at 15:32
  • well then they're very much going against the whole concept of SEO – annakata Jan 05 '09 at 15:39
  • 4
    Yeah not really good for SEO but good for the end user when bookmarking etc, for example updating a page title when the hash in the URL changes, or when using HTML5/JS `window.history` its good to update page title as well as URL – rmorse Apr 29 '13 at 11:36
  • See googles own documentation on crawling javascript applications https://developers.google.com/webmasters/ajax-crawling/ – codewizard Oct 29 '14 at 17:10
  • "This recommendation is officially deprecated as of October 2015" – David Spector Jan 20 '20 at 22:48
46

Use document.title.

See this page for a rudimentary tutorial as well.

Gerold Broser
  • 11,355
  • 4
  • 36
  • 85
lc.
  • 105,606
  • 20
  • 147
  • 176
42

The code is
document.title = 'test'

MineCMD
  • 394
  • 4
  • 13
Kev
  • 14,115
  • 14
  • 75
  • 106
  • 3
    I use top.document.title to reference to window itself (I have framesets...) – Dror Jan 05 '09 at 15:29
  • 2
    @AdrianoVaroliPiazza no need to go -1 though, what about applications which do not require SEO or what about websites which actually make use of some HTML5 functions. I mean if you set up your website properly and make use of ajax and have a fallback for non-js/crawlers this will only speedup the user experiance and also keep the matching title visible. Seems like a good idea to me. – Mathijs Segers Aug 07 '13 at 08:59
  • Don't you need to add a `;` to the end? – MineCMD Mar 03 '16 at 21:26
  • 1
    @MineCMD, a semicolon (;) is only required if you have multiple commands on a single line. Assuming that you don't have something holding the command open (a dot, quote, double quote, left brace, etc.) then a newline is considered to be the ending of the command. I'm not sure how true this is in the case of old browsers but it has proven to be true in recent versions of both Chrome and Firefox. (I don't use IE or Edge so am unable to say on them) – Wayne Mar 27 '16 at 06:57
  • @Wayne Somewhat-correct; there are some edge cases where ASI leads to unexpected (by most) behavior, particularly if you're returning an anonymous object. – Dave Newton May 07 '18 at 19:49
20

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);
});
Braden Best
  • 7,664
  • 3
  • 29
  • 42
  • 1
    I found the perfect word for the caveat with method 1: `undefined behavior`. – Braden Best Feb 19 '14 at 18:17
  • 1
    This absolutely _should_ be downvoted. Method 1 is undefined behavior, like noted above (and no amount of disclaimers will justify mentioning it); also, `document.querySelector.apply`, seriously? – Andrey Tarantsov Feb 29 '16 at 07:31
  • 3
    @AndreyTarantsov no amount of disclaimers will justify mentioning it? How about mentioning it so that people know what NOT to do? We learn from our mistakes, so telling someone not to mention something that is a mistake, is bad advice. Also, this is a really old answer (literally one of the first answers I wrote on this site), so that "seriously?" was unnecessary. You can't possibly know what has changed in my knowledge and experience over the past three years. – Braden Best Feb 29 '16 at 08:02
11

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.

TheTXI
  • 36,035
  • 10
  • 82
  • 110
10

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

dimitry_n
  • 2,569
  • 1
  • 25
  • 41
4

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.

Bryan Denny
  • 26,451
  • 32
  • 103
  • 124
3

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'));
mel3kings
  • 6,989
  • 3
  • 54
  • 60
3

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>
goblin01
  • 63
  • 4
3

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";
kleopatra
  • 49,346
  • 26
  • 88
  • 189
2

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.

dougd_in_nc
  • 359
  • 5
  • 19
  • 2
    _"To see the pages as Google sees 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."_ - this is a **very** good approach when developing SEO friendly AJAX-heavy websites. – John Weisz Mar 14 '15 at 16:57
  • 1
    On one of my sites, Google has indexed tons of documents which were discoverable only via ajax. Good approach, but don't rely on it as adverse solution if you want to hide it from crawlers. – Alex Khimich Jan 15 '21 at 19:12
2

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.

yazzer
  • 493
  • 5
  • 9
2

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.

Rich
  • 876
  • 6
  • 15
0

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.

shootingrubber
  • 145
  • 4
  • 12
0

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

Pbearne
  • 875
  • 2
  • 10
  • 24
0

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!

Hamed
  • 537
  • 3
  • 14
-1

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

-1

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" );
?>
D. Henry
  • 9
  • 3