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

How to prevent any iframe or any other script to change title of document in the top window?

本文关键字:任何 窗口 标题 顶部 文档 iframe 何防止 其他 脚本      更新时间:2023-09-26

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

有什么方法可以预防吗?

谢谢,

将观察者与title元素挂钩。我在下面修改了MDN的例子:

// 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>

你试过吗?:

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