如何为新的浏览器标签设置标题?

邦琼

我对链接的新标签有疑问。

无论如何,在用户单击链接之前,我是否可以设置浏览器选项卡标题?如果新标签中包含的html不具有title属性,则似乎无法辩论新标签的标题。我对吗?如何设置标题?

//the href is dynamic so I can't set them one by one because I have 100+ html file here
<a href="test.html" target="_blank">open me<a>
Rhumborl

有了它,这是不可能的,因为您的链接只是普通的HTML链接。当新页面在新选项卡中打开时,当前页面将没有任何引用,因此无法以任何方式对其进行更改。您将需要使用javascript打开页面并以这种方式设置标题。

您可以动态地设置它window onload以查找所有a标签并添加click事件,从而打开窗口并设置标题。

如果每个页面需要不同的标题,则可以将其存储data-a标记属性中

请注意,这仅适用于相同域中的页面(出于安全性考虑),并且不能右键单击并按“在新窗口中打开”来处理用户。但是,Windows中的中键单击似乎确实起作用。

的HTML

<a href="test.html" data-title="A new page" target="_blank">open me</a>

的JavaScript

window.addEventListener("load", function() {

    // does the actual opening
    function openWindow(event) {
        event = event || window.event;

        // find the url and title to set
        var href = this.getAttribute("href");
        var newTitle = this.getAttribute("data-title");
        // or if you work the title out some other way...
        // var newTitle = "Some constant string";

        // open the window
        var newWin = window.open(href, "_blank");

        // add a load listener to the window so that the title gets changed on page load
        newWin.addEventListener("load", function() {
            newWin.document.title = newTitle;
        });

        // stop the default `a` link or you will get 2 new windows!
        event.returnValue =  false;
    }

    // find all a tags opening in a new window
    var links = document.querySelectorAll("a[target=_blank][data-title]");
    // or this if you don't want to store custom titles with each link
    //var links = document.querySelectorAll("a[target=_blank]");

    // add a click event for each so we can do our own thing
    for(var i = 0; i < links.length; i++) {
        links[i].addEventListener("click", openWindow.bind(links[i]));
    }

});

样本JsFiddle

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在浏览器的新标签页(_blank)中设置打开pdf文件的标题

如何添加新的浏览器标签

如何在MVC Web应用程序中设置浏览器标签页标题?

如何为网站添加浏览器标签图标(图标)?

如何为边缘浏览器设置分配的访问权限

如何为不同的浏览器设置不同的高度?

如何为所有浏览器设置图像高度?

如何设置窗口特定的浏览器操作按钮标题

如何在浏览器中设置PDF文件的标题?

如何在joomla浏览器标题上更改标题标签

如何设置浏览器?

如何为标签项的标题设置样式?

如何使用Selenide等待相同的浏览器标签标题文本?

设置书签页面以在Opera浏览器的新标签页中打开

浏览器标签中的标题错误R闪亮

HTML href >link text</a> 与浏览器“标签标题”不同

在Firefox / Chrome上打开新标签页或窗口时,如何获得新的浏览器会话?

如何关闭浏览器标签

Laravel-如何为浏览器提供新的laravel项目

如何为海豚文件浏览器设置Win + E快捷方式

CSS:如何为浏览器屏幕设置内容的固定宽度

如何为Chromium嵌入式浏览器的不同实例设置不同的Cookie

如何为Safari Web浏览器设置媒体查询

如何为远程Web驱动程序设置所需功能的多个浏览器名称

在浏览器中为Ionic应用设置标题

如何为启动器而不是活动标题设置不同的标签?

如何设置PhantomJS的浏览器语言

如何设置默认浏览器?

如何设置浏览器窗口的ID?