Clicking the button becomes impossible after entering text and using `evaluateJavascript`

I am currently working on finding a solution to input the receipt number and click the 'Check Status' button on this specific website:

After successfully entering the receipt number:

document.getElementById('receipt_number').value = '\(receiptNumber)';

The issue arises when the 'Check Status' button remains disabled even after the input. To enable the button, the following code can be used:

document.getElementsByName('initCaseSearch')[0].removeAttribute("disabled");

Despite enabling the button, it still cannot be clicked due to errors showing as 'undefined'. It seems that the webpage has additional logic or validation preventing automated form submission. I have attempted to resolve this by submitting the form using the following code:

document.forms[0].submit();

However, this action results in the page reloading without processing the inputted receipt number.

If anyone has any suggestions or ideas on how to overcome this obstacle, please share them with me!

Answer №1

When dealing with a website that uses a ReactJS app, traditional methods like evaluateJS may not work effectively. In such cases, utilizing WKScriptMessageHandler could be a better approach.

To achieve similar functionality in the browser, consider the following code snippet:

const element = document.querySelector("input#receipt_number");
const propertyNames = Object.keys(element);

let reactProps;
for (const propName of propertyNames) {
  if (propName.startsWith('__reactProps$')) {
    reactProps = propName;
    break;
  }
}

if (reactProps) {
  const onChangeHandler = element[reactProps]?.onChange;

  if (typeof onChangeHandler === 'function') {
    const event = {
      target: {
        value: "abc1234567891", // enter your custom values here
      },
    };

    onChangeHandler.call(element, event);

    const buttonElement = document.querySelector("button[type='submit']");
    if (buttonElement && buttonElement[reactProps]?.onClick) {
      buttonElement[reactProps].onClick({preventDefault:()=>{}});
    }
  }
}

It is essential to customize the value and adjust the code based on specific requirements.

**Update : **

For a recommended approach using WKScriptMessageHandler, consider the following sample code:

import WebKit

class MyScriptMessageHandler: NSObject, WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        // Handle the message received from JavaScript
        if let messageBody = message.body as? String {
            // Perform actions based on the message content
            if messageBody == "triggerEvent" {
                // Trigger React event or modify component state here
                if let element = webView.evaluateJavaScript("document.querySelector(\"input#receipt_number\")") as? WKScriptValue,
                   let reactProps = (element.propertyNames.first { $0.hasPrefix("__reactProps$") }) as? String,
                   let onChangeHandler = element.valueForKey(reactProps + ".onChange") as? WKScriptValue {
                    let event = webView.evaluateJavaScript("new Event('change')") as? WKScriptValue
                    onChangeHandler.call(withArguments: [event])
                }

                if let buttonElement = webView.evaluateJavaScript("document.querySelector(\"button[type='submit']\")") as? WKScriptValue,
                   let reactProps = (buttonElement.propertyNames.first { $0.hasPrefix("__reactProps$") }) as? String,
                   let onClickHandler = buttonElement.valueForKey(reactProps + ".onClick") as? WKScriptValue {
                    onClickHandler.call()
                }
            }
        }
    }
}

// Create the WKWebView configuration
let webConfiguration = WKWebViewConfiguration()

// Create an instance of your custom script message handler
let scriptMessageHandler = MyScriptMessageHandler()

// Add the script message handler to the user content controller
webConfiguration.userContentController.add(scriptMessageHandler, name: "myMessageHandler")

// Create the WKWebView with the configuration
let webView = WKWebView(frame: .zero, configuration: webConfiguration)

// Inject the JavaScript code into the WKWebView
let javascriptCode = """
// Add an event listener to trigger the message to the native code
document.querySelector("button").addEventListener("click", function() {
    window.webkit.messageHandlers.myMessageHandler.postMessage("triggerEvent");
});
"""

let userScript = WKUserScript(source: javascriptCode, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(userScript)

// Load your desired URL in the WKWebView
if let url = URL(string: "https://egov.uscis.gov/") {
    let request = URLRequest(url: url)
    webView.load(request)
}

Caution : Use this code responsibly and avoid any automation that may compromise site validation processes or engage in illegal activities.

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

The Next.js bundle analyzer is failing to generate pages for viewing bundles

I'm currently working on optimizing the bundle size of my website by utilizing https://www.npmjs.com/package/@next/bundle-analyzer However, when I execute npm analyze with "analyze": "cross-env ANALYZE=true next build", The HTML ...

Generating an <article> with React to encapsulate elements

I'm attempting to generate a list of 'cards', each consisting of three elements. The parent component, ItemCard, produces the following structure: <> <article> <ItemName data={items} /> ...

What's the simplest method for adjusting the default font in Reactstrap?

Currently working on a MERN project and I want to customize the font used by Reactstrap for my React frontend. While I've come across solutions for altering Bootstrap 4's default fonts, I'm unsure how to implement them in Reactstrap. Any gui ...

Implementing Image Data in AngularJS: A Guide to Binding Images to IMG Tags

Allow me to explain the problem further. I am retrieving a user's profile picture by calling an API that returns image data, as shown in the screenshot below https://i.stack.imgur.com/t8Jtz.jpg https://i.stack.imgur.com/pxTUS.png The reason I canno ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

Tips for retrieving the checked status of a Material UI <Checkbox/> component and changing it to false upon clicking a different icon (such as a delete icon)

Greetings! I have encountered a problem that I am hoping someone can assist me with. I am looking for information or guidance on how to handle a specific issue. The challenge I am facing involves accessing the checked property of a material-ui <Checkbo ...

Using jQuery's .grep() method on an array will only return the final digit

Could someone help me understand the behavior of jQuery's .grep() method? I'm creating a jQuery object array based on the names of these elements: <div class="small1 other">S1</div> <div class="small2">S2</div> <div c ...

My MERN stack web application is experiencing difficulties running due to an error stating "Invalid hook call - mismatching React and React DOM"

I am a novice in JavaScript and have been struggling to understand why my web application is failing at runtime. Despite trying everything I could think of, the issue persists. In my build process, I typically use the npm ci command to install packages for ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Understanding the use of `useState` within the lifecycle of a React

I'm eager to dive into the lifecycle of a React functional component. Many resources outline these three key steps: 1-mounting 2-rendering 3-unmounting. But what about other code that is written before the useEffect() function, like this example: ...

How can I run `npm run dev` in Vite after deleting both the `package-lock.json` and `package.json` folders?

Currently, I am following a YouTube tutorial on coding and deploying a React website. My project was created using Vite and everything looked good in my browser window initially. However, after closing the terminal, my browser displayed "This page can&apos ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

The functionality of the Ajax script seems to be optimized for Firefox browsers exclusively, as it is encountering issues with compatibility on other

My code works perfectly in Firefox, but I'm encountering an issue in all other browsers. Specifically, I'm getting the error message "SyntaxError: JSON Parse error: Unexpected EOF" on line if (this.readyState == 4 && this.status == 200). ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

What is the best way to locate a function (whether it be a GET, POST, etc.) within index.js using an Express router

I've been trying to set up a router in Express, following a tutorial. However, my code can't seem to find the function get/users. Interestingly, it works fine when I include it in index.js index.js : const express = require('express' ...

React Material Design Cards for Responsive Layouts

Hi there, I am currently navigating my way through Material Design and attempting to ensure that the cards section is responsive by utilizing media queries and flex. However, I have encountered an issue where only a portion of the image is displayed when t ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...