Managing a webpage using Xcode and Swift's UIWebView

Recently, I developed a straightforward application that guides users to a web-based platform. One of the app's pages allows users to search for store stock from various stores by manually inputting the store number or utilizing automatic location detection. After inputting the appropriate barcode, users are directed back to the UIWebView. However, I encountered an obstacle when trying to automatically populate the barcode into a specific div field and execute a JavaScript function. Despite attempting to use evaluatejavascript without much success, I haven't lost hope and seek assistance!

The view controller code is outlined below:

import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WebView

    @IBOutlet weak var searchText: UITextField!

    required init(coder aDecoder: NSCoder) {
        self.webView = WebView()
        super.init(coder: aDecoder)!
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.setPosition(view)
    }

   // Further actions and functions are defined in the code...

Answer №1

Take a look at this question along with the following responses:

Calling Javascript using UIWebView

  1. Start by creating a JavaScript method to handle the barcode input.
  2. If the page has already loaded, you can invoke the method using stringByEvaluatingJavaScriptFromString.

    let codebar = "34244342342424234" webView.stringByEvaluatingJavaScriptFromString("methodName("\(codebar)");")


Update

I previously utilized this approach: evaluateJavaScript in WKWebView, where an example loads jQuery and modifies the background color:

var navigator : WKWebView!

func runJS(js:String) {
    navigator.evaluateJavaScript(js) {
        res, error in
        print(res ?? "no result", error ?? "no error")
    }
}

@IBAction func changeBackground(_ sender: Any) {
    navigator.evaluateJavaScript("jQuery('body').css('background', 'magenta!important')") {res, error in print(error ?? "no error buton 1")}
}


@IBAction func loadJQuery(_ sender: Any) {
    //Load jQuery library using plain JavaScript
    runJS(js: "(function(){ " +
        "var newscript = document.createElement('script'); " +
        "newscript.type = 'text/javascript'; " +
        "newscript.async = true; " +
        "newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'; " +
        "(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript); " +
    "})();")
}

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

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

Effective methods for transferring parameters between two separate JavaScript files within an express.js application

Currently, I am working with Express.js and facing a challenge in passing parameters from one JavaScript file to another. How can this be accomplished? The two files involved are 1. process.js var WebPageTest = require('webpagetest'); var wpt ...

What is the best way to manage a new Error in Node.js while utilizing ES6 Symbols?

In my node.js application, I am implementing an endpoint using ES6 Symbols. Here is an example: // ES6 Symbol Method const taskCreationMethod = { [Symbol.taskMethod]() { return { storeCheckFunc: async function(storeId, employeeId) ...

Changing date and time into milliseconds within AngularJS

Today's date is: var timeFormat = 'dd MMM, yyyy hh:mm:ss a'; var todayDate = dateFormat(new Date(), timeFormat); Can we convert today's date to milliseconds using AngularJS? Alternatively, how can we use the JavaScript function getT ...

invoke the modal function from a separate React file

I am currently studying react and nextjs. I am experimenting with calling a modal from another file but unfortunately it's not functioning as expected. Here is the code I used: Signin.js import { Modal } from "react-bootstrap"; import { u ...

What is the best way to update placeholders in Angular 8+?

I have a collection of items: a = ['apple', 'mango', 'grape', 'papaya', 'banana', 'cucumber']. An input element is present with a placeholder stating select from fruits (the array elements should ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

What is AngularJs's preference: URL or ID for templateUrl?

When looking at the AngularJS documentation, you will come across an example using the templateUrl property: In the HTML: //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> And in the controller: . ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

Show a success message once the jQuery Ajax operation is successful and then refresh the page

I am looking to implement a feature where a Bootstrap alert message is shown immediately following a successful AJAX request and page refresh. success: function(res) { window.location.reload(); $('#success').html('<div class=&qu ...

Issue with interaction between jQuery AJAX and PHP login functionality

Currently, I am attempting to implement an inline login feature that triggers whenever the PHP $_SESSION['logged_in'] variable is not defined (this variable gets set when a user logs in). The challenge arises when I try to keep the user on the sa ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

Fill the drop-down menu with the present day's date, month, and year

I'm new to this, so please bear with me. I have some html and jQuery code: $(document).ready(function() { var d = new Date(); var month = d.getMonth() + 1; var year = d.getFullYear(); $("#month").val(month); $("#year").val(year) ...

What could be the reason my Angular interceptor isn't minified correctly?

I have come across this interceptor in my Angular project: angular.module('dwExceptionHandler', []) .factory('ExceptionInterceptor', ['$q', function ($q) { return function (promise) { return promise.th ...

Why isn't my div displaying in JavaScript?

Currently working on a project for the Odin Project front-end web development. My task involves creating a grid using javascript/jQuery. I attempted to use the createElement method but have encountered an issue in making the div visible within the html. Am ...

Sequelize.js - Establishing Relationships Between Two Tables

Technologies used: Node.js, Express.js, Sequilize.js I am facing a challenge in connecting two tables within my project. The tables in question are the user table and the color table. Each color is associated with a user, where a single user can have onl ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Exploring the Fusion of Strings and Arrays of Javascript Objects using jQuery and JSON

Trying to achieve a simple task, but not very proficient in jQuery so struggling to figure it out. Want to send JSON data to an ASP.NET Controller. Data includes strings and a list of objects. The code snippet would appear like this: View: $(document). ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

Guide on crafting a scrollable and touch-responsive grid using CSS and JavaScript

I am seeking guidance on creating a grid with a variable number of columns and rows. It should be contained within a separate div and should not interfere with other objects or alter the parent's size. The grid needs to be square and I am currently u ...