通常,我只是删除并重新定义title属性,如下面的代码。
if (delete document.title) {
Object.defineProperty(document, 'title', {
get: getter,
set: setter,
enumerable: true,
configurable: false
});
}
但是,我发现某些页面仍然可以使用以下代码来更改标题。
$(window.top.document.head).find('title').text('New Title')
有没有办法阻止它?
谢谢,
答案 0 :(得分:1)
将观察者挂钩到title元素。我在下面修改了MDN's example:
// select the target node
var target = document.getElementsByTagName("title");
console.log(target[0]);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert("Title changed!");
// Treat the mutation here. Use mutation.type to see what happened.
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target[0], config);
function changeTitle(){
document.title = "Something else";
}

<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>A test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<a href="" onclick="changeTitle();">Change title</a>
</body></html>
&#13;
答案 1 :(得分:0)
你试过这个吗?:
$("head title").bind("DOMSubtreeModified", function(e){ /* switch back to original title*/});