ecoe
ecoe

Reputation: 5322

Reload html page with new title

I have same page (or anchor tag) links in a single html document. When a user clicks these links, they open that same html document in a new tab.

How can that new tab have a new document title?

The problem with my code below is that it renames the current tab's title (not the new one just opened). There is a default title for my page that I want to have when you first load the page. Of course, all subsequent new pages loaded set this for their title.

<title>Default title</title>
<a href=#relativeLink target='_blank' onclick="return runMyFunction();">click me</a>

<script>
    function runMyFunction() {
        document.title="new title!"
        return true;
    }
</script>

Upvotes: 0

Views: 390

Answers (2)

Cruiser KID
Cruiser KID

Reputation: 1280

There are two ways to accomplish this 1, Passing title as Url Parameter 2, Save all titles in an Array and passing selected title index of titles array

<html>
  <head>
    <title>Default title</title>
  </head>
<body>
    <a href="?newTitle=My new title" target="_blank" >newTitle equal to My title 1</a>
    <a href="?newTitle=My new title 2" target="_blank" >newTitle equal to My title 2</a>
    <a href="?newTitle=My new title3" target="_blank" >newTitle equal to My title 3</a>
    <br />
    <a href="?tIdx=0" target="_blank" >tIdx equal to 0</a>
    <a href="?tIdx=1" target="_blank" >tIdx equal to 1</a>
    <a href="?tIdx=3" target="_blank" >tIdx equal to 2</a>
    <script>

        var titles = ["title 1", "title 2", "title 3" , "title 4"];


        function getUrlParameterValueByName(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        }

        var newTitleValue = getUrlParameterValueByName('newTitle');
        var titleIndex = getUrlParameterValueByName('tIdx');
        if (newTitleValue)
            document.title = newTitleValue;
        if (titleIndex)
            document.title = titles[titleIndex];


    </script>
</body>
<html>

Upvotes: 1

Collector
Collector

Reputation: 2094

If the new tab opened is a page you make, change the title there as the page is loaded. You can check the referrer. If the new tab is an external page whose title you cannot change, you could simply create your own page which shows the external page inside an iframe.

<title>My Title</title>
<iframe src="/path/to/external" />

Upvotes: 0

Related Questions