Finding the next occurrence of a word in a search using UIWebView poses a challenge

I have developed a simple UIWEBVIEW app that showcases HTML content inside a UIWEBVIEW. Within the Webview, there is a JavaScript application integrated with my Xcode project that highlights selected words when a user inputs and clicks on a "Net" button. I am now working on implementing a "next" UIButton that will scroll down to the next highlighted word in the application. Below is the relevant JavaScript code:

UIWEBVIEWSEARCH.JS


        // JavaScript function for highlighting all occurrences of a keyword
        // Implementing functionality to navigate to the next highlighted word
        ...
    

A snippet from the XCODE file SearchWebView.M:


        // Implementation of methods to interact with JavaScript functions
        // Including highlighting occurrences and navigating to the next result
        ...
    

The issue I am facing is whether I have correctly declared the 'GoNext' function in my code. Currently, nothing happens when trying to go to the next highlighted word. Any assistance or guidance on this matter would be greatly appreciated. Thank you!

Answer №1

    //   The following code was implemented for Next and Previous functionality and it is working effectively
     //  function

 uiWebview_HighlightAllOccurencesOfNextStringForElement(element,keyword) {

        if (element) {
            if (element.nodeType == 3) {        // Text node
                while (true) {
                    //if (counter < 1) {
                    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("span");
                    var text = document.createTextNode(value.substr(idx,keyword.length));
                    span.appendChild(text);
                    span.setAttribute("class","MyAppHighlight");
                    text = document.createTextNode(value.substr(idx+keyword.length));
                    element.deleteData(idx,value.length-idx);
                    var next = element.nextSibling;
                    element.parentNode.insertBefore(span,next);
                    element.parentNode.insertBefore(text,next);
                    element = text;
                    span.scrollIntoView();
                    span.style.backgroundColor = "yellow";

                    span.style.color = "black";
                    a.push(span);

                    uiWebview_SearchResultCount++;



                }
            } 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--) {
                        uiWebview_HighlightAllOccurencesOfNextStringForElement(element.childNodes[i],keyword);
                    }
                }
            }
        }
    }

    // the main entry point to start the search
    function uiWebview_HighlightAllOccurencesOfNextString(keyword) 
    `enter code here`{
        uiWebview_RemoveAllHighlights();
        uiWebview_HighlightAllOccurencesOfNextStringForElement(document.body, keyword.toLowerCase());

    }






//In Your ViewContrlller, call this function on Next And Previous button method


    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {
        [self highlightAllOccurencesOfNextString:searchbar.text];
    }

    - (NSInteger)highlightAllOccurencesOfNextString:(NSString*)str
    {
        NSString *filePath = [[NSBundle mainBundle]pathForResource:@"UIWebViewSearch" ofType:@"js"];
        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
        NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
        [htmlWebView stringByEvaluatingJavaScriptFromString:jsString];

        NSString *startSearch = [NSString stringWithFormat:@"uiWebview_HighlightAllOccurencesOfNextString('%@')",str];
        [htmlWebView stringByEvaluatingJavaScriptFromString:startSearch];
        NSString *result = [htmlWebView stringByEvaluatingJavaScriptFromString:@"a.length"];
        currentPosition = [result intValue] - 1;
        return [result integerValue];

    }

    -(void)nextMethod
    {
        currentPosition -= 1;
        NSString *nextScrollPosition =  [NSString stringWithFormat:@"a[%d].scrollIntoView()", currentPosition];
        [htmlWebView stringByEvaluatingJavaScriptFromString:nextScrollPosition];
    }

    -(void)previousMethod
    {
        currentPosition += 1;
        NSString *previousScrollPosition =  [NSString stringWithFormat:@"a[%d].scrollIntoView()", currentPosition];
        [htmlWebView stringByEvaluatingJavaScriptFromString:previousScrollPosition];
    }

Answer №2

Instead of relying on the functions goNext and goPrev in your JavaScript file, consider utilizing the function "highlightAllOccurencesOfNextString." This function will meet your needs, and you can then implement the next and previous methods from my solution on the button actions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to switch out all instances of "GET" methods with "POST" throughout the codebase?

While working on a web application, we encountered caching issues with Internet Explorer (caching occurred due to the use of GET requests). The problem was resolved when users turned on "Always refresh from server" in IE's Developers Tool. Although we ...

The phenomenon of componentDidMount being triggered before the DOM is fully mounted arises when utilizing createPortal in React

I have written a React code snippet that looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) ...

JSF CommandLink malfunctions on Firefox when reRendering an entire form

I am currently working on a JSF 1.2 application (Sun RI, Facelets, Richfaces) that was previously designed only for IE6 browsers. However, we now need to extend our support to include Firefox as well. On one of the pages, there is a form with a button tha ...

The elements within my custom UITableViewCell (designed using Storyboard) are unexpectedly empty

I've successfully customized a table view cell for my iPhone application by following these steps. First, I designed a prototype cell in the storyboard and added a UILabel and a UIImageView. Next, I created a new file and made it a subclass of UITab ...

Screen rendering can be a challenging task

As I dive into learning how to use THREE.js for creating browser games, I've encountered a roadblock. Every time I attempt to import a model using the code, the screen just renders black. Surprisingly, I've been smoothly coding and running it in ...

When the enter key is pressed, the form will be submitted and the results will be displayed in a modal window without

Behold, my unique form! It lacks the traditional <form></form> tags. <input id="query" name="query" style="font-size: 18pt" id="text" data-email="required" type="text" placeholder="Search Here from <?php echo $row['no']."+"; ?& ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

Creating a dynamic form field using JavaScript

I'm struggling with a JavaScript issue that requires some assistance. I have a form sending an exact number of inputs to be filled to a PHP file, and now I want to create a preview using jQuery or JavaScript. The challenge lies in dynamically capturin ...

Adjust Position of Text on nvd3 Line Chart

Is there a way to rotate the x-axis labels by 90 degrees? I am experiencing issues with them overlapping. I have attempted to use the rotateLabels option, but it doesn't seem to be working as expected. <nvd3-line-chart data="singleLineChartD ...

Numerous instances of a specific custom directive in Angular2

I'm in the process of developing an Angular application, focusing on creating highly reusable code using directives (as components). <div class="container container-fluid" > <div class="row"> <table class="table table-responsive ...

Apply jQuery styling to new select box on page in order to maintain consistent styling throughout

I've encountered an issue with my jQuery select box styling. It appears to work perfectly on the initial page load, but when new content containing a select box is dynamically loaded onto the page, the styling doesn't get applied to it. Can anyo ...

Resolving JAR Dependencies in the /usr/share/java Directory

Could you shed some light on how JAR files and the Java class loader utilize the directory /usr/share/java? Is this a unique location where the JVM automatically loads JAR files and looks up classes, or is there more to it? Let's say we have two JAR ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Transferring ExpressJS API scripts to the Server for Deployment

After developing a basic API with ExpressJS to interact with MongoDB for CRUD operations, I successfully ran it locally using the command "npm nodemon" in the source folder. Testing it with Postman confirmed its functionality. Now, my concern is how to dep ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

Converting a script.js document ready function wrapper and jquery plugin methods to be compatible with React (version 16.12.0)

I'm in the process of converting an older script.js file that is used to select HTML elements in conjunction with $ jquery into React. I want to export/import it into a page component using the componentDidMount() method and pass it to jquery. However ...

Tips for handling errors when the ID parameter in the URL doesn't correspond to the ID in the database and redirecting to an error page

Utilizing a MERN stack application, I rely on the Axios library to facilitate communication between the client and server. An essential route '/blogs' is responsible for fetching all the blogs from the backend and presenting them on the interface ...

Ways to indicate the language of your website to the Chrome browser for the translate bar

I am experiencing a unique situation with my web app where it appears to be in one language but the Chrome translate bar identifies it as being written in Estonian. Despite trying methods such as lang and xml:lang, the Google translation bar does not seem ...

After triggering the ClickAndHold action with the Action Class, how can I navigate to the second level of the bottom menu and successfully click on the

{ actions.clickAndHold(element).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.DOWN) .sendKeys(Keys.ENTER).perform(); } view image description ...

What steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...