0

I'm new to Javascript. I want to add an icon to all my project's web pages. This icon changes accordingly to whoever logs in in my page. What i'm trying now is, in master page load (when i have all of its data in codebehind, including his chosen icon), i introduced a js function to change icon:

    (function icon(image) {
        var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.hre = image;
        document.getElementsByTagName('head')[0].appendChild(link);
    })();

(adapted from here: Changing website favicon dynamically)

im trying to call this function with Page.ClientScript.RegisterStartupScript() method:

  (protected void Page_Load(object sender, EventArgs e)
  {
  if (!Page.IsPostBack)
     {
        //...

        UserModel usuario = (UserModel)Session["usuario"];

        //...

        Page.ClientScript.RegisterStartupScript(this.GetType(), "icone", $"icone({(Bitmap)new ImageConverter().ConvertFrom(usuario.imagem)});", true);
     }
  }

The method is simply not executing(its not returning error either, it just "jump it"), and i sincerely have no idea why.

OOOOR, there may be a better way to do it, but i just cant figure it.

For the record, i DONT have the icons/images on a folder. I MUST get them form the database.

(I will later add validation for when user has no image in database. Assume for now it will never be null).

  • Wouldn't it be easier to simply create an action that returns the image and put that as the href of the `shortcut-icon` directly instead of resorting to Javascript? – Christoph Herold Mar 27 '19 at 20:12

2 Answers2

0

A few things need to be edited:

First, think you got the parameters for RegisterStartupScript not set as required. The 3rd value should be the javascript code to run. You can add the entire script as a variable (as indicated here: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerstartupscript?view=netframework-4.7.2), or you can add your function in <script>...</script> tags to the HTML page, and then just call the function from within RegisterStartupScript (as the 3rd parameter value)

Secondly, there's a typo in your JavaScript function:

link.hre = image; should be link.href = image;

Thirdly, (this part might require some work) the image has to be a URL (string) to the actual image (Not the binary Bitmap)... you might first have to save the image to the web server as a .jpg or .png and use its URL to there, or you have to convert the image to Base64 and add the image via Data URLs https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

Finally, you modified the JavaScript from the original example (you mentioned) In this case, you want to send the image URL as a parameter to the function icon However, the icon function is encapsulated. So the function is basically in a Private scope. Remove the encapsulation around the function if needed to be called from another function on the page... hope this make sense.

D.B.
  • 1,792
  • 1
  • 10
  • 13
0

Instead of using Javascript, you could simply link your shortcut-icon to a handler, that immediately returns the image. (The following code is not tested, it's there to describe the basic process!)

In your page:

<link rel="shortcut icon" type="image/x-icon" href="/userimage.ashx">

userimage.ashx:

<%@ WebHandler Language="C#" Class="UserImageHandler" %>

userimage.ashx.cs:

using System;
using System.Web;

public class UserImageHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/png"; // or image/jpg, image/bmp, ...
        var image = FetchImageFromDatabase(context.User.Identity.Name); // your logic for fetching the image from the database
            // You could also return a default image here, if the user has not selected one.
        context.Response.Write(image); // Write the binary data to the response stream.
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}
Christoph Herold
  • 1,799
  • 13
  • 18