Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the favicon appear in a new window?

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 but the favicon doesn't show. This is the code and the jsFiddle: https://jsfiddle.net/ufnjspgc/

function Start() {

  $('#TheButton').click(function() {

    var TheHeadHTML = '<link href="' + window.location.protocol + '//' + window.location.host + '/favicon.ico" rel="icon" type="image/x-icon">';
    TheHeadHTML = TheHeadHTML + '<title>Title Works</title>';

    var TheNewWindow = window.open();

    $(TheNewWindow.document.head).html(TheHeadHTML);
  });
}

$(Start);

How do you make the favicon appear in the new window?

like image 240
frenchie Avatar asked Oct 21 '16 12:10

frenchie


1 Answers

You can open a new window using a data URI. Here's the code:

<input type="button" value="test" id="TheButton" />

function Start() {

  $('#TheButton').click(function() {
    var TheNewWindow = window.open("data:text/html;charset=utf8,<html><head><link href='" + window.location.protocol + "//" + window.location.host + "/favicon.ico' rel='icon' type='image/x-icon'><title>Title Works</title></head><body></body></html>");
  });
}

$(Start);

And the fiddle.

Basically, data URIs allow you to specify the content in the URL itself such that it doesn't need to go to a server, or, in your case, to the "about:blank" resource browsers (must) have. "about:blank" can cause a lot of problems when scripting because of cross-origin and other concerns.

As noted by @ConnorsFan, this technique does not work in IE. As indicated in this question by Diego Mijelshon, IE does not allow navigation to a data URI, and thus it cannot be used as the URL for a new window. Seems to work fine in recent versions of Chrome and Firefox. I'm afraid I don't have a copy of Safari on which to test.

like image 126
Heretic Monkey Avatar answered Sep 29 '22 11:09

Heretic Monkey