[UWP] Stop GIF Animation in WebView of UWP

Md. Niaz Mahmud 171 Reputation points
2021-07-13T11:26:30.167+00:00

Hi, I am using a webview in my UWP application where a gif image will be provided from external web. There is a requirement that, I need to stop the GIF animation after staying 5 seconds on the page. How can I accomplish this??? I was looking for injecting Java Script, but couldn't find out the actual way . Can anyone help please???

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,851 Reputation points
    2021-07-14T06:51:52.53+00:00

    Hello, Welcome to Micorosoft Q&A,

    For this scenario, a common workaround is to use InvokeScriptAsync with the JavaScript eval function to use the HTML event handlers

    For stopping Gif, you could use the following javascript method.

    [].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);  
    function is_gif_image(i) {  
        return /^(?!data:).*\.gif/i.test(i.src);  
    }  
      
    function freeze_gif(i) {  
        var c = document.createElement('canvas');  
        var w = c.width = i.width;  
        var h = c.height = i.height;  
        c.getContext('2d').drawImage(i, 0, 0, w, h);  
        try {  
            i.src = c.toDataURL("image/gif");   
        } catch (e) {   
            for (var j = 0, a; a = i.attributes[j]; j++)  
                c.setAttribute(a.name, a.value);  
            i.parentNode.replaceChild(c, i);  
        }  
    }  
    

    And inject it with the eval function 5 seconds after the page is Navigation Completed.

    private async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)  
    {  
        await Task.Delay(TimeSpan.FromSeconds(5));  
        var function = @"[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);  
    function is_gif_image(i) {  
        return /^(?!data:).*\.gif/i.test(i.src);  
    }  
    function freeze_gif(i) {  
        var c = document.createElement('canvas');  
        var w = c.width = i.width;  
        var h = c.height = i.height;  
        c.getContext('2d').drawImage(i, 0, 0, w, h);  
        try {  
            i.src = c.toDataURL('image / gif');   
        } catch (e) { // cross-domain -- mimic original with all its tag attributes  
            for (var j = 0, a; a = i.attributes[j]; j++)  
                c.setAttribute(a.name, a.value);  
            i.parentNode.replaceChild(c, i);  
        }}";  
      
        await MyWebView.InvokeScriptAsync("eval", new string[] { function });  
    }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful