pzeszko
pzeszko

Reputation: 2119

Making document.title untouchable for Javascript

Is it possible to make document.title (<head><title> .. </title></head>) impossible to change for Javascript ?

My problem is that iny my project there are some javascripts that change document.title every 1 second and I want title to stay the same. Unfortuantely I am not able to change or remove those JS files. I've tried a to think of workaround, something like that :

function checkTitle() {
if(document.title != oldTitle)
document.title = oldTitle;
}
setInterval(checkTitle(), 100);

It seems like a good idea, BUT unfortuantely there I have also counter which displays timer on my site. My whole code looks like this :

var ticks = 0;

function update() {
    if(ticks % 1000 == 0) {
    ...update timer and some other stuff...
    }
    ticks+=100;
    if(document.title != oldTitle)
    document.title = oldTitle;
}
setInterval(update, 100);

Such code after +- 100 seconds is beggining to slow down and my timer definitely is not updated every 1 second.

So the question is : Is it possible to make html element (..) impossible to change for javascript, if not, is there any workaround for my problem ?

Thanks in advance.

Upvotes: 18

Views: 1332

Answers (2)

Tyr
Tyr

Reputation: 2810

You can bind the following events to your title tag to prevent changing itself:

$(document).ready(function() {
    $('title').bind('DOMSubtreeModified propertychange', function() {
        var title = $('title');
        if(title.text() != 'old title')
        {
            alert('title changed');
        }
    });

    $('a').bind('click', function() {
        $('title').text('new title');
    });
});

Upvotes: 1

adeneo
adeneo

Reputation: 318182

This probably has some side effects, but I'm not sure what exactly, but you can redefine the title property and make it non-writable, which would be better than sealing or freezing the entire document as it only affects the title

Object.defineProperty(document, 'title', {
  enumerable: false,
  configurable: false,
  writable: false,
  value: document.title
});

FIDDLE

This should work in all browser from IE9 and up, and maybe IE8, which I haven't tested, but I think only DOM nodes can be changed in IE8, and not sure if document counts ?

Upvotes: 25

Related Questions