Reputation: 31
The problem is that I have a component(which is not my code, so I can't change it) that calls document.title="". Of course I won't allow that, so my plan is to override the document.title method and check for an empty string. But how do I handle a call that sets the document.title = Correct Title, with the overriden method.
Here is my code so far:
var actualTitle = document.title;
Object.defineProperty(document, 'title', {
set: function (newValue) {
if(newValue != ""){
document.title = newValue;
}
},
get: function () {
return actualTitle;
}
});
This code makes an infinite loop, because the method calls it self. But I need to actually set the title inside the set method.
Is there some sort of super method I can use, like you can in for example Java.
Upvotes: 2
Views: 964
Reputation: 35481
You can stop modification of the title simply by making the property non-writable (which is the default), and giving it the value you'd like:
function lockDocumentTitle() {
// extract the initial value
var actualTitle = document.title;
// override the property to always have that value
Object.defineProperty(document, 'title', {
value: actualTitle,
/*
By default:
- not enumerable
- not configurable
- not writable
*/
});
}
console.log(document.title); // ''
document.title = 'Test';
console.log('Set to ' + document.title); // 'Test'
lockDocumentTitle();
document.title = 'Something Else'; // no effect
console.log('Still ' + document.title); // its still 'Test'
Upvotes: 1
Reputation:
Object.defineProperty(document, 'title', {
set: function (newValue) {
if(newValue != ""){
document.getElementsByTagName("title")[0].innerHTML = newValue;
}
},
get: function () {
return document.getElementsByTagName("title")[0].innerHTML;
}
});
How it works:
When I use Object.defineProperty
, the page's title won't change when you use document.title = "lorem ipsum dolor sit amet"
. So, let's hack it.
We still have another way to change the title: document.getElementsByTagName("title")[0].innerHTML
. So, let's change the value of document.getElementsByTagName("title")[0].innerHTML
every time the value of document.title
is changed. But you hate document.title = ""
so let's ignore this by if(newValue != "")
Upvotes: 3
Reputation: 672
Will a simple flag do?
var actualTitle = document.title,
isModified = false;
Object.defineProperty(document, 'title', {
set: function (newValue) {
isModified = true;
if(newValue != "" && !isModified){
document.title = newValue;
}
},
get: function () {
return actualTitle;
}
});
Upvotes: 0