使 document.title 对于 Javascript 来说是不可触碰的

Making document.title untouchable for Javascript

本文关键字:title document 对于 Javascript      更新时间:2023-09-26

是否可以使Javascript无法更改document.title<head><title> .. </title></head>)?

我的问题是,在我的项目中,有一些javascript每1秒更改一次document.title,我希望标题保持不变。不幸的是,我无法更改或删除这些JS文件。我尝试过想办法,像这样:

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

这似乎是一个好主意,但不幸的是,我也有计数器在我的网站上显示计时器。我的整个代码看起来像这样:

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);

+- 100 秒后的此类代码开始变慢,我的计时器肯定不会每 1 秒更新一次。

所以问题是:是否有可能使 html 元素 (..) 无法更改为 javascript,如果没有,我的问题有什么解决方法吗?

提前谢谢。

这可能有一些副作用,但我不确定具体是什么,但您可以重新定义 title 属性并使其不可写,这比密封或冻结整个文档更好,因为它只影响title

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

小提琴

这应该适用于IE9及更高版本的所有浏览器,也许还有IE8,我还没有测试过,但我认为在IE8中只能更改DOM节点,并且不确定document是否算数?

您可以将以下事件绑定到标题标签以防止更改自身:

$(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');
    });
});