如何防止任何iframe或任何其他脚本在顶部窗口中更改文档的标题?

时间:2015-09-30 12:08:27

标签: javascript html5

通常,我只是删除并重新定义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')

有没有办法阻止它?

谢谢,

2 个答案:

答案 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;
&#13;
&#13;

答案 1 :(得分:0)

你试过这个吗?:

$("head title").bind("DOMSubtreeModified", function(e){ /* switch back to original title*/});