Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds:

var item = 'apple';
if(document.body.innerHTML.toString().indexOf(item) > -1){
    setTimeout(function() {
        alert(item + " was found");
    }, 150);
}else{
    setTimeout(function()
               {
        location.reload(true);
    }, 4000);
}

The functionality of this code was flawless. However, I wanted to enhance it by enabling it to search for multiple items using an array:

var item = [
    'apple',
    'peach'
];
for (var i = 0; i < item.length; i++){
    if(document.body.innerHTML.toString().indexOf(item[i]) > -1){
        player.play();
        setTimeout(function() {
            var curitem = item[i];
            alert(item[i] + " was found");
        }, 200);
    }
}
//else{
//    setTimeout(function()
//               {
//        location.reload(true);
//    }, 4000);
//}

After implementing this multi-item search functionality, I encountered two challenges:

  1. How can I modify the script to display the exact item from the array that has been found? Currently, the alert message displays as 'undefined was found', even though the script successfully identifies the items.
  2. In case none of the items are found, how do I trigger a page refresh?

Answer №1

When it comes to accomplishing this task, there are several methods one can use. Personally, I find that using regex is the most efficient approach as it provides more control and is generally faster than traditional looping techniques, especially when dealing with a large number of terms.

Take for example the following code snippet:

var items = [
    'apple',
    'peach'
];
var itmRegEx = new RegExp (`(${ items.join("|") })`);

var itmMtch  = document.body.innerHTML.match (itmRegEx);
if (itmMtch  &&  itmMtch.length) {
    //player.play();
    //setTimeout (alert, 200, itmMtch[1] + " was found");
    setTimeout (console.log, 200, itmMtch[1] + " was found");
}
else {
    console.log ("Reloading...");
    //setTimeout ( () => {location.reload (true);}, 4000);
}

Key points to consider:

  1. toString() method is not required in this scenario.
  2. Regex offers extensive capabilities such as matching expressions like 'apple\\b', which specifically targets "apple" without including "apples".
  3. Exercise caution when using innerHTML as it may match unintended elements like
    <a href="virusserver.net/badapple">free!</a>
    . To avoid this, utilize textContent if the desired content is visible on the page.
  4. Take note of the updated version of the setTimeout() function used in the script.
  5. Target specific nodes of interest by class or id instead of casting a broad net with document.body to enhance performance.
  6. Special care is needed when working with location.reload as the parameterized form of setTimeout() may lead to an "Illegal invocation" error.

Answer №2

This script is designed to locate the first instance of a specific item within an array. The content div identifier is crucial in this example as the script is embedded within the body of the snippet.

var fruits = [
    'apple',
    'peach'
];

// Creating a regular expression pattern using the array items
var fruitPattern = new RegExp(fruits.join("|"));
var searchResult = document.getElementById("content").innerHTML.toString().match(fruitPattern);

if (searchResult) {
  //player.play();
  setTimeout(function() {
    alert(searchResult.toString() + " was found");
  }, 200);
} else {
  setTimeout(function() {
    location.reload(true);
  }, 4000);
}
<div id="content">gfg</div>

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

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

AngularJS does not allow access to the variable value outside of the resource service's scope,

I have developed an AngularJS factory service to handle REST calls. The service is functioning correctly, but I am facing a challenge where I need to set values into $scope.variable and access them outside of the resource service. However, when attempting ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

What is the best way to track the loading progress of an AJAX page in WordPress?

On my WordPress blog, I utilize a plugin known as Advanced Ajax Page Loader. This handy tool loads the next page or post through AJAX and then places it in a specific div on my site. However, I am now interested in incorporating a progress bar to show the ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

"Error encountered when attempting to execute the delete() function in Django

Having some trouble with my delete function. It successfully deletes the object but does not redirect to window.location as expected. Instead, I'm getting an error message: DoesNotExist at /api/personnel/delete/ Resource matching query does not exist ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

JavaScript keydown event for rotating images

I am experiencing an issue with JavaScript animation. I have incorporated code from this particular link into my keydown function. However, the code is not functioning as expected. While the code from the provided link works fine on its own, within the key ...

AngularJS, sort through "afoo" excluding "foo"

I am attempting to implement a filter within an ng-repeat Main.HTML <table> <tr ng-repeat="param in MyParam | filter: UnrequestValue"> <td>{{param.Label}}</td> </tr> </table> Main.js MyParam: ...

Implementing the fetch API with radio buttons in a React Native application

I found a useful package for radio buttons called react-native-flexi-radio-button. Currently, I'm working on displaying API results within radio buttons. The API response provides 4 options, and my goal is to render text alongside the corresponding ra ...

Frequent execution of jQuery Ajax requests is evident

Using a live operator, I attach a click function to a li-element: $(".UListView li input.iconbutton.click").live("click", function(e){ e.preventDefault(); [...] $.get("ajax/categorylist.php?appendcategories=true&parentcat="+currentid+"&side="+sid ...

AngularJS experiencing issues with Bootstrap multiselect functionality

I am currently integrating bootstrap-multiselect into my AngularJS application. To do this, I've included the following scripts in my master page (index.html). <script src="/bower_components/jquery/dist/jquery.min.js"></script> <scrip ...

The Javascript calculation function fails to execute proper calculations

I have been facing immense frustration while working on a project lately. The project involves creating a unique Webpage that can calculate the total cost for users based on their selections of radio buttons and check boxes. Assuming that all other functi ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...