How to make the favicon appear in a new window?

后端 未结 7 1558
无人共我
无人共我 2021-01-17 22:17

I\'m opening a new window into which I\'m injecting HTML for both the body and the head. The problem is in the head section: the HTML includes both the title and the favicon

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 23:00

    If the favicon is from your own Web site, you can create a print.html template page that contains the favicon link (with an id attribute):

    
    
    
        
    
    
    
    
    

    When the button is clicked, you open that page and inject the additional content in the head and body sections. According to my tests, the presence of the favicon link in the DOM is a good indicator to determine when the page content can be modified. For Chrome and Firefox, the changes can be made in $(wnd).load(). For Internet Explorer 11, they can be made in $(wnd.document).ready().

    $("#btnOpenWindow").click(function () {
        var done = false;
    
        // Open the window with the empty page
        var wnd = window.open("print.html");
    
        // For Chrome and Firefox
        $(wnd).load(function () {
            injectContent();
        });
    
        // For Internet Explorer
        $(wnd.document).ready(function () {
            injectContent();
        });
    
        function injectContent() {
            // If the favicon link is loaded in the DOM, the content can be modified
            if (!done && $("#favicon", wnd.document).length > 0) {
                done = true;
                $("head", wnd.document).append("The window title");
                $("body", wnd.document).append("

    Main title

    "); ... } } });

    If you really need to modify the favicon of the new window, you can use the same method as above, with the following changes:

    
    
    function injectContent() {
        if (!done) {
            var $favicon = $("#favicon", wnd.document);
            if ($favicon.length > 0) {
                done = true;
                var faviconUrl = window.location.protocol + "//" + window.location.host + "/favicon.ico";
                $favicon.attr("href", faviconUrl);
                $("head", wnd.document).append("The window title");
                $("body", wnd.document).append("

    Main title

    "); ... } } }

提交回复
热议问题