programing

웹 사이트 favicon 동적 변경

copysource 2023. 2. 3. 23:20
반응형

웹 사이트 favicon 동적 변경

현재 로그인한 사용자에 따라 브랜드가 지정된 웹 응용 프로그램이 있습니다.페이지의 favicon을 프라이빗 라벨의 로고로 변경하고 싶은데 코드나 예를 찾을 수 없습니다.누가 이걸 성공적으로 해 본 적이 있나요?

폴더에 12개의 아이콘이 있는 것을 상상하고 있으며, 사용하는 favicon.ico 파일의 참조는 HTML 페이지와 함께 동적으로 생성됩니다.생각?

왜 안 되나요?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

다음은 Firefox, Opera 및 Chrome에서 작동하는 코드입니다(여기에 게시된 다른 모든 답변과 달리).IE11에서도 동작하는 코드의 데모를 다음에 나타냅니다.다음 예는 Safari 또는 Internet Explorer에서 작동하지 않을 수 있습니다.

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'dynamic-favicon';
 link.rel = 'shortcut icon';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}

그런 다음 다음과 같이 사용합니다.

var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
 changeFavicon('http://www.google.com/favicon.ico');
};

포크이동하거나 데모를 봅니다.

다음의 HTML 스니펫이 있는 경우:

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

예를 들어 JQuery를 사용하는 경우, 이 링크의 HREF 요소를 변경하여 Javascript를 사용하여 favicon을 변경할 수 있습니다.

$("#favicon").attr("href","favicon2.png");

또한 Favicon Defender와 마찬가지로 캔버스 요소를 만들고 HREF를 캔버스의 ToDataURL()로 설정할 수도 있습니다.

jQuery 버전:

$("link[rel='shortcut icon']").attr("href", "favicon.ico");

또는 그 이상:

$("link[rel*='icon']").attr("href", "favicon.ico");

Vanilla JS 버전:

document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";

document.querySelector("link[rel*='icon']").href = "favicon.ico";

보다 현대적인 접근법:

const changeFavicon = link => {
  let $favicon = document.querySelector('link[rel="icon"]')
  // If a <link rel="icon"> element already exists,
  // change its href to the given link.
  if ($favicon !== null) {
    $favicon.href = link
  // Otherwise, create a new element and append it to <head>.
  } else {
    $favicon = document.createElement("link")
    $favicon.rel = "icon"
    $favicon.href = link
    document.head.appendChild($favicon)
  }
}

그런 다음 다음과 같이 사용할 수 있습니다.

changeFavicon("http://www.stackoverflow.com/favicon.ico")

여기 favicon을 이모티콘 또는 텍스트로 만들기 위한 작은 조각이 있습니다.스택 오버플로우일 때 콘솔에서 동작합니다.

function changeFavicon(text) {
  const canvas = document.createElement('canvas');
  canvas.height = 64;
  canvas.width = 64;
  const ctx = canvas.getContext('2d');
  ctx.font = '64px serif';
  ctx.fillText(text, 0, 64);

  const link = document.createElement('link');
  const oldLinks = document.querySelectorAll('link[rel="shortcut icon"]');
  oldLinks.forEach(e => e.parentNode.removeChild(e));
  link.id = 'dynamic-favicon';
  link.rel = 'shortcut icon';
  link.href = canvas.toDataURL();
  document.head.appendChild(link);
}

changeFavicon('❤️');

favicon은 다음과 같이 헤드 태그에 선언됩니다.

<link rel="shortcut icon" type="image/ico" href="favicon.ico">

보기 데이터에서 원하는 아이콘의 이름을 전달하고 헤드 태그에 넣을 수 있습니다.

오페라, 파이어폭스, 크롬 파비콘IE(사파리)으로 Chrome은 Chrome)가 업데이트될 때만 합니다.iframe 안에 등)은 내가알 수 한.

var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
    change: function(iconURL) {
        if (arguments.length == 2) {
            document.title = optionalDocTitle}
        this.addLink(iconURL, "icon")
        this.addLink(iconURL, "shortcut icon")

        // Google Chrome HACK - whenever an IFrame changes location 
        // (even to about:blank), it updates the favicon for some reason
        // It doesn't work on Safari at all though :-(
        if (!IE) { // Disable the IE "click" sound
            if (!window.__IFrame) {
                __IFrame = document.createElement('iframe')
                var s = __IFrame.style
                s.height = s.width = s.left = s.top = s.border = 0
                s.position = 'absolute'
                s.visibility = 'hidden'
                document.body.appendChild(__IFrame)}
            __IFrame.src = 'about:blank'}},

    addLink: function(iconURL, relValue) {
        var link = document.createElement("link")
        link.type = "image/x-icon"
        link.rel = relValue
        link.href = iconURL
        this.removeLinkIfExists(relValue)
        this.docHead.appendChild(link)},

    removeLinkIfExists: function(relValue) {
        var links = this.docHead.getElementsByTagName("link");
        for (var i=0; i<links.length; i++) {
            var link = links[i]
            if (link.type == "image/x-icon" && link.rel == relValue) {
                this.docHead.removeChild(link)
                return}}}, // Assuming only one match at most.

    docHead: document.getElementsByTagName("head")[0]}

favicon을하려면 favicon으로 합니다.favicon.change("ICON URL")상기의 사용법을 사용해 주세요.

(이 코드에 대해서는, http://softwareas.com/dynamic-favicons 를 참조해 주세요).

또는 이모티콘을 원하는 경우:)

var canvas = document.createElement("canvas");
canvas.height = 64;
canvas.width = 64;

var ctx = canvas.getContext("2d");
ctx.font = "64px serif";
ctx.fillText("☠️", 0, 64); 

$("link[rel*='icon']").prop("href", canvas.toDataURL());

https://koddsson.com/posts/emoji-favicon/에 대한 소품

이것을 IE에 유효하게 하는 유일한 방법은 *.ico 요청을 처리하도록 웹 서버를 설정하고 서버 측 스크립트 언어(PHP, .NET 등)를 호출하는 것입니다.또한 *.ico를 셋업하여 단일 스크립트로 리다이렉트하고 이 스크립트가 올바른 favicon 파일을 전송하도록 합니다.같은 브라우저에서 다른 favicon 사이를 왔다 갔다 할 수 있다면 캐시에 대한 흥미로운 문제가 있을 것입니다.

Greg의 어프로치를 사용하고, favicon.ico용의 커스텀 핸들러를 작성합니다(간단화) 핸들러는 다음과 같습니다.

using System;
using System.IO;
using System.Web;

namespace FaviconOverrider
{
    public class IcoHandler : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/x-icon";
        byte[] imageData = imageToByteArray(context.Server.MapPath("/ear.ico"));
        context.Response.BinaryWrite(imageData);
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public byte[] imageToByteArray(string imagePath)
    {
        byte[] imageByteArray;
        using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
        {
        imageByteArray = new byte[fs.Length];
        fs.Read(imageByteArray, 0, imageByteArray.Length);
        }

        return imageByteArray;
    }
    }
}

그런 다음 IIS6에서 웹 구성의 httpHandlers 섹션에서 해당 핸들러를 사용하거나 IIS7에서 'Handler Mappings' 기능을 사용할 수 있습니다.

jQuery를 사용하는 사용자를 위한 단일 라인 솔루션이 있습니다.

$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');

사이트를 개발할 때는 항상 이 기능을 사용합니다.그래서 로컬, 개발 또는 프로드가 실행되고 있는 탭을 한눈에 볼 수 있습니다.

이제 Chrome은 SVG favicon을 지원하므로 훨씬 더 쉬워졌습니다.

Tampermonkey 스크립트

https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f에서 검색한 데모 사이트를 가리키는 탬퍼몬키 스크립트는 https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f에서 확인할 수 있습니다.

기본코드

다른 답변에서 이것을 수정하면 개선될 수 있지만 내 필요에 충분히 부합한다.

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

자신의 SVG(툴을 사용하는 경우 Jake Archibald의 SVGOMG로 클리닝)를 맨 위에 있는 경찰서에 삽입하기만 하면 됩니다.viewBox 속성을 사용하여 정사각형인지 확인하고 바로 사용할 수 있는지 확인하십시오.

대부분의 경우 favicon은 이렇게 선언됩니다.

<link rel="icon" href"...." />

이렇게 하면 이것으로 참조할 수 있습니다.

const linkElement = document.querySelector('link[rel=icon]');

이걸로 사진을 바꿀 수 있어요.

linkElement.href = 'url/to/any/picture/remote/or/relative';

WikiPedia에 따르면 로드하는 favicon 파일을 지정할 수 있습니다.link를 달다head는 「」)rel="icon"

예를 들어 다음과 같습니다.

 <link rel="icon" type="image/png" href="/path/image.png">

그 콜에 대해 다이내믹한 콘텐츠를 작성하려면 쿠키에 액세스하여 세션 정보를 가져오고 적절한 콘텐츠를 표시할 수 있습니다.

파일 형식이 잘못될 수 있습니다(IE는 파일 형식만 지원합니다).ICO 포맷, 그 외의 대부분은 PNG 및 GIF 이미지를 지원하며 브라우저와 프록시를 통해 문제를 캐싱할 수 있습니다.이는 favicon의 원래 반복 때문이며, 특히 사이트의 미니로고로 북마크를 표시하기 위한 것입니다.

네, 충분히 가능합니다.

  • favicon.ico 뒤에 쿼리 문자열을 사용합니다(및 기타 파일 링크 - 아래 응답 링크 참조).
  • 서버가 올바른 이미지 파일(스태틱라우팅 규칙 또는 다이내믹서버측 코드)로 「someUserId」에 응답하고 있는 것을 확인하기만 하면 됩니다.

예.

<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">

어떤 서버언어/프레임워크를 사용하든 userId를 기반으로 파일을 쉽게 검색하여 요청에 따라 제공할 수 있습니다.

그러나 favicon(실제로 매우 복잡한 주제)을 제대로 하려면 , https://stackoverflow.com/a/45301651/661584 를 참조해 주세요.

모든 세부사항을 스스로 해결하는 것보다 훨씬 쉬워요.

즐거운 시간 되세요.

프로젝트에는 favico.js를 사용합니다.

Favicon을 사전 정의된 도형 범위 및 사용자 정의 도형으로 변경할 수 있습니다.

내부적으로는canvas렌더링 및base64아이콘 인코딩용 데이터 URL.

라이브러리에는 아이콘 배지와 애니메이션도 있습니다.웹캠 비디오를 아이콘으로 스트리밍할 수도 있다고 합니다.

2021년에 Chrome에서 제안된 솔루션을 테스트한 결과, 링크가 변경되어도 브라우저가 favicon을 캐시하고 변경을 표시하지 않는 경우가 있습니다.

이 코드는 동작했습니다(이전 제안과 유사하지만 캐시를 피하기 위해 임의 매개 변수를 추가합니다).

let oldFavicon = document.getElementById('favicon')
var link = document.createElement('link')
link.id = 'favicon';
link.type = 'image/x-icon'
link.rel = 'icon';
link.href = new_favicon_url +'?=' + Math.random();
if (oldFavicon) {
    document.head.removeChild(oldFavicon);
}
document.head.appendChild(link);

https://gist.github.com/mathiasbynens/428626#gistcomment-1809869에서 복사하여 다른 사용자가 같은 문제를 겪고 있는 경우

언급URL : https://stackoverflow.com/questions/260857/changing-website-favicon-dynamically

반응형