locked
Highlight the text in web view RRS feed

  • Question

  • Hi,

    I'm loading html content in web view. I need to highlight the some words into it. How can i do it.

    Please help me anyone.

    Friday, March 1, 2013 2:59 PM

Answers

  • Inject javascript into the webview:

    http://blogs.msdn.com/b/wsdevsol/archive/2012/10/18/nine-things-you-need-to-know-about-webview.aspx


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, March 1, 2013 3:01 PM
    Moderator
  • Finally i found the solution to set the bacground color in the js, in the next of this line : 

    results += escape(leftNeighText + text.nodeValue + rightNeighText) + ";";
     

    var ea = document.getElementsByClassName('MyAppHighlight');
     for (var i = 0; i < ea.length; i++) {
     ea[i].style.backgroundColor = 'yellow';
     };


    • Marked as answer by Purusp Wednesday, March 6, 2013 11:33 AM
    Wednesday, March 6, 2013 11:32 AM

All replies

  • Inject javascript into the webview:

    http://blogs.msdn.com/b/wsdevsol/archive/2012/10/18/nine-things-you-need-to-know-about-webview.aspx


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, March 1, 2013 3:01 PM
    Moderator
  • I have a javascript file in my project solution explorer, how to invoke this script file into webview.
    Monday, March 4, 2013 9:28 AM
  • Load the contents of your javascript file into a string, then inject it.


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, March 4, 2013 3:29 PM
    Moderator
  • I'm using the below javascript code to highlight text but i can't able to get success.

    // We're using a global variable to store the number of occurrences
    var MyApp_SearchResultCount = 0;
    
    var console = "\n";
    var results = "";
    
    var neighSize = 20;
    
    // helper function, recursively searches in elements and their child nodes
    function MyApp_HighlightAllOccurencesOfStringForElement(element,keyword) {
        if (element) {
            if (element.nodeType == 3) {// Text node
                while (true) {
                    var value = element.nodeValue;  // Search for keyword in text node
                    var idx = value.toLowerCase().indexOf(keyword);
                                                    
                    if (idx < 0) break;             // not found, abort
                    
                    var span = document.createElement("highlight");
                    span.className = "MyAppHighlight";
                    var text = document.createTextNode(value.substr(idx,keyword.length));
                    span.appendChild(text);
                    
                    var rightText = document.createTextNode(value.substr(idx+keyword.length));
                    element.deleteData(idx, value.length - idx);
                                    
                    var next = element.nextSibling;
                    element.parentNode.insertBefore(rightText, next);
                    element.parentNode.insertBefore(span, rightText);
                    
                    var leftNeighText = element.nodeValue.substr(element.length - neighSize, neighSize);
                    var rightNeighText = rightText.nodeValue.substr(0, neighSize);
                  
                   
                    element = rightText;
                    MyApp_SearchResultCount++;	// update the counter
                    
                    console += "Span className: " + span.className + "\n";
                    console += "Span position: (" + getPos(span).x + ", " + getPos(span).y + ")\n";
                    
                    results +=escape(leftNeighText + text.nodeValue + rightNeighText) + ";";
                   
                    results;
                }
            } else if (element.nodeType == 1) { // Element node
                if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
                    for (var i=element.childNodes.length-1; i>=0; i--) {
                        MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
                    }
                }
            }
        }
    }
    
    function getPos(el) {
        // yay readability
        for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
        return {x: lx,y: ly};
    }
    
    // the main entry point to start the search
    function MyApp_HighlightAllOccurencesOfString(keyword) {
        MyApp_RemoveAllHighlights();
        
        MyApp_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
      
    }
    
    // helper function, recursively removes the highlights in elements and their childs
    function MyApp_RemoveAllHighlightsForElement(element) {
        if (element) {
            if (element.nodeType == 1) {
                if (element.getAttribute("class") == "MyAppHighlight") {
                    var text = element.removeChild(element.firstChild);
                    element.parentNode.insertBefore(text,element);
                    element.parentNode.removeChild(element);
                    return true;
                } else {
                    var normalize = false;
                    for (var i=element.childNodes.length-1; i>=0; i--) {
                        if (MyApp_RemoveAllHighlightsForElement(element.childNodes[i])) {
                            normalize = true;
                        }
                    }
                    if (normalize) {
                        element.normalize();
                    }
                }
            }
        }
        return false;
    }
    
    // the main entry point to remove the highlights
    function MyApp_RemoveAllHighlights() {
        MyApp_SearchResultCount = 0;
        MyApp_RemoveAllHighlightsForElement(document.body);
    }

    C# code

    string varMySheet = "var mySheet = document.styleSheets[0];";
                string addCSSRule = @"function addCSSRule(selector, newRule) {""if (mySheet.addRule) {""mySheet.addRule(selector, newRule);""} else {""ruleIndex = mySheet.cssRules.length;""mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);""}""}";
                string setHighlightColorRule = "addCSSRule('highlight', 'background-color: yellow;')";
                MyWebview.InvokeScript(varMySheet, null);
                MyWebview.InvokeScript(addCSSRule, null);
                MyWebview.InvokeScript(setHighlightColorRule, null);
                MyWebview.InvokeScript("MyApp_HighlightAllOccurencesOfString", new string[] { "Nikon" });
    Is there anyother way to highlight the web view text?

    Tuesday, March 5, 2013 2:17 PM
  • Does your highlight code work if it's already in the webpage?  You should test it there first.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Tuesday, March 5, 2013 3:25 PM
    Moderator
  • Yes. The below html code i'm loading into web view.

    <?xml version="1.0" encoding="UTF-8"?>
    <html>
        <head>
     <meta charset="utf-8" />
      <title>Matt's Webview Content Page</title>
     <script lang="en-us" type="text/javascript">
         var MyApp_SearchResultCount = 0;
         var console = "\n";
         var results = "";
         var neighSize = 20;
         // helper function, recursively searches in elements and their child nodes
         function MyApp_HighlightAllOccurencesOfStringForElement(element, keyword) {
             if (element) {
                 if (element.nodeType == 3) {// Text node
                     while (true) {
                         var value = element.nodeValue;  // Search for keyword in text node
                         var idx = value.toLowerCase().indexOf(keyword);
    
                         if (idx < 0) break;             // not found, abort
    
                         var span = document.createElement("highlight");
                         span.className = "MyAppHighlight";
                         var text = document.createTextNode(value.substr(idx, keyword.length));
                         span.appendChild(text);
    
                         var rightText = document.createTextNode(value.substr(idx + keyword.length));
                         element.deleteData(idx, value.length - idx);
    
                         var next = element.nextSibling;
                         element.parentNode.insertBefore(rightText, next);
                         element.parentNode.insertBefore(span, rightText);
    
                         var leftNeighText = element.nodeValue.substr(element.length - neighSize, neighSize);
                         var rightNeighText = rightText.nodeValue.substr(0, neighSize);
    
    
                         element = rightText;
                         MyApp_SearchResultCount++;	// update the counter
    
                         console += "Span className: " + span.className + "\n";
                         console += "Span position: (" + getPos(span).x + ", " + getPos(span).y + ")\n";
    
                         results += escape(leftNeighText + text.nodeValue + rightNeighText) + ";";
    
                         results;
                     }
                 } else if (element.nodeType == 1) { // Element node
                     if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
                         for (var i = element.childNodes.length - 1; i >= 0; i--) {
                             MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i], keyword);
                         }
                     }
                 }
             }
         }
         function getPos(el) {
             // yay readability
             for (var lx = 0, ly = 0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
             return { x: lx, y: ly };
         }
         // the main entry point to start the search
         function MyApp_HighlightAllOccurencesOfString(keyword) {
    
             MyApp_RemoveAllHighlights();
    
             MyApp_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
    
         }
         // helper function, recursively removes the highlights in elements and their childs
         function MyApp_RemoveAllHighlightsForElement(element) {
             if (element) {
                 if (element.nodeType == 1) {
                     if (element.getAttribute("class") == "MyAppHighlight") {
                         var text = element.removeChild(element.firstChild);
                         element.parentNode.insertBefore(text, element);
                         element.parentNode.removeChild(element);
                         return true;
                     } else {
                         var normalize = false;
                         for (var i = element.childNodes.length - 1; i >= 0; i--) {
                             if (MyApp_RemoveAllHighlightsForElement(element.childNodes[i])) {
                                 normalize = true;
                             }
                         }
                         if (normalize) {
                             element.normalize();
                         }
                     }
                 }
             }
             return false;
         }
         // the main entry point to remove the highlights
         function MyApp_RemoveAllHighlights() {
             MyApp_SearchResultCount = 0;
             MyApp_RemoveAllHighlightsForElement(document.body);
         }
     </script>
    </head>
        <body>
    				<link type="text/css" rel="stylesheet" href="http://eservice-public.s3.amazonaws.com/lib/javascript/slides-0.1/photoswipe-3.0.4/photoswipe.css"/>
    				<link type="text/css" rel="stylesheet" href="http://eservice-public.s3.amazonaws.com/lib/javascript/slides-0.1/slides.css"/>
    				<script src="http://eservice-public.s3.amazonaws.com/lib/javascript/slides-0.1/photoswipe-3.0.4/lib/klass.min.js"> </script>
    				<script src="http://eservice-public.s3.amazonaws.com/lib/javascript/slides-0.1/photoswipe-3.0.4/code.photoswipe-3.0.4.min.js"> </script>
    				<script src="http://eservice-public.s3.amazonaws.com/lib/javascript/slides-0.1/slides.js"> </script>
    				<h1>Voorwoord</h1>
    				<p>Het is weer gelukt! Een Magazine van 80 pagina’s vol met zeer interessante, leuke en leerzame artikelen.
    Dat NCN vijfentwintig jaar bestaat kan u inmiddels niet ontgaan zijn. In dezeuitgave een terugblik op deze vijfentwintig jaar door Hans Braakhuis. Tevens een
    uitnodiging voor onze verjaardagsborrel in Utrecht.Naast dit stukje clubgeschiedenis een interview met ons tweeduizendste lid, een artikel over geboortefotografie, fotografie in het koude noorden van Finland en
    nog veel, veel meer! Een bijzonder fraaie uitgave van het Magazine, voor mij een mooi moment om het stokje door te geven. Begin 2009 ben ik samen met Cees en Onno begonnen
    met het restylen van het toenmalige clubblad. In september van dat jaar viel de eerste uitgave van het NCN Magazine op de mat bij iets meer dan 800 leden.
    Nu ruim drie jaar en 14 uitgaven verder zet ik er een punt achter. Vanaf maart dit jaar is er steeds meer verantwoordelijkheid overgedragen aan
    Sascha. Vanaf de volgende uitgave zal de hele productie door haar gecoördineerd worden. Ik wens haar net zoveel plezier bij het organiseren en opmaken als dat ik
    er de afgelopen tijd aan gehad heb. Graag wil ik hierbij iedereen bedanken die de afgelopen tijd een bijdrage heeft geleverd aan het Magazine, want zonder deze
    mensen kan een Magazine zoals deze niet bestaan. Blijf dit dus ook vooral doen! Groet en tot ziens, Richard Stuur je artikelen voor het maart Magazine vóór 1 februari naar
    <a href="mailto:redactie@nikon-club-nederland.nl">redactie@nikon-club-nederland.nl</a></p>
          </body>
    </html>

    after loading above html content, user click search button i just invoke the script

    MyWebview.InvokeScript("MyApp_HighlightAllOccurencesOfString", new string[] { "het" });

    Now i need to highlight the "het" word in the web view control.

    Please tell me what i'm missing.

    • Marked as answer by Purusp Wednesday, March 6, 2013 11:32 AM
    • Unmarked as answer by Purusp Wednesday, March 6, 2013 11:32 AM
    Wednesday, March 6, 2013 7:18 AM
  • Finally i found the solution to set the bacground color in the js, in the next of this line : 

    results += escape(leftNeighText + text.nodeValue + rightNeighText) + ";";
     

    var ea = document.getElementsByClassName('MyAppHighlight');
     for (var i = 0; i < ea.length; i++) {
     ea[i].style.backgroundColor = 'yellow';
     };


    • Marked as answer by Purusp Wednesday, March 6, 2013 11:33 AM
    Wednesday, March 6, 2013 11:32 AM
  • Since we're discussing WebView, I want to point out that I am giving a "Chalk-talk" on the subject of WebView.  It's free and you can come prepare with questions.  http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/5d6a079e-3a85-40bd-adc7-3994f311c08b

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, April 12, 2013 6:11 PM
    Moderator