The functionality of receiving javascript messages in Swift is currently not functioning as expected

The issue I'm facing is that the JavaScript message is not being sent to Swift as expected.

Here's the Swift Code:

class FirstViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {

@IBOutlet weak var webview: WKWebView!

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
     print( "Enter here" )

    if message.name == "jsHandler" {
        print( message.body );
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "web")
    let url = URL(fileURLWithPath: htmlPath!)
    let request = URLRequest(url: url)

    let user = WKUserContentController()
    user.add(self, name: "jsHandler")
    webview.configuration.userContentController = user

    webview.uiDelegate = self
    webview.navigationDelegate = self
    webview.load(request)
}

And here's the JavaScript code:

$(document).on( 'click', '.element', function() {
    window.webkit.messageHandlers.jsHandler.postMessage( "Invoke swift" );
} );

I'm wondering if there might be something wrong with this setup or if I'm missing a crucial step. Any help would be greatly appreciated!

Answer №1

To integrate Storyboard, simply include the following code snippet within the viewDidLoad method prior to calling webview.load(request)

//Assuming 'webview' is your @IBOutlet
webview.configuration.userContentController.add(self, name: "yourHandler")
webview.configuration.preferences.javaScriptEnabled = true

Answer №2

I managed to find a solution that worked for me.

Although I can't say it's the best approach, it solved my problem.

The WKWebView requires a configuration when it starts, so I had to create it through code instead of using the graphical interface.

//@IBOutlet weak var webview: WKWebView!
var wk: WKWebView!

Within the viewDidLoad function:

let config = WKWebViewConfiguration()
let user = WKUserContentController()

user.add(self, name: "jsHandler")
config.userContentController = user

wk = WKWebView(frame: .zero, configuration: config)
view.addSubview(wk)

let layoutGuide = view.safeAreaLayoutGuide

wk.translatesAutoresizingMaskIntoConstraints = false
wk.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
wk.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
wk.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
wk.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

With this setup, it is now possible for JavaScript to communicate with Swift!

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

Using angular.copy function to copy an array with a custom property

Let's use the example below to illustrate an issue: var ar = [4, 2, 3]; ar.$x = 'something'; var br = angular.copy(ar); console.dir(br); After copying ar to br, the $x property is no longer present. This is because when Angular copies an a ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

Creating a series of adjacent dropdown menus with JavaScript, HTML, and CSS

I am encountering an issue while attempting to place multiple dropdown menus next to each other. I have included two categories as dropdown options in the header, but I am facing difficulty with one of them not functioning correctly. When I click on the no ...

Adding styles in NextJS based on multiple conditions

Within my nextjs application, I have implemented a custom <Button> component that dynamically adjusts its background-color and text-color based on the selected theme. To achieve this, I defined a stylesheet named Button.module.css: .btn { font-si ...

Can a Unicode character be overwritten using a specific method?

Is there a way to display a number on top of the unicode character '♤' without using images? I have over 200 ♤ symbols each with a unique number, and using images would take up too much space. The characters will need to be different sizes, a ...

What steps do I need to follow in order to set up webpack.config.js to convert my HTML file to JS in a Reactjs application

My current folder structure is shown below: https://i.sstatic.net/mSdcH.png Upon attempting to run my React app, I encountered the following error: Failed to compile. ./src/css/owl.html 1:0 Module parse failed: Unexpected token (1:0) To resolve this is ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

Adjusting CSS to switch up the color scheme

Is there a way to allow users to change the background color of pull quotes by using the input type="color tag within a form element? Below is my current HTML structure: <form action="change.php" method="post"> name: <input type="text"> ...

Angularjs directive retrieves infowindow DOM element from Google Maps

In order to apply some style fixes to the Infowindow, I am trying to select the element with the class 'gm-style-iw'. This selection process is taking place within an angularjs directive. <div ui-view="full-map" id="full-map" class="mainMap c ...

Automatically create subclasses and reclassify object lists with CanJS

My CanJS script receives a list of results from a remote JSONP server in this format: [ { "class": "ABaseClass", "value": "1"}, { "class": "ASubClass", "value": "2"}, { "class": "ABaseClass", "value": "3"}, { "class": "ASubClass", "value": ...

Tips for deleting a single item from an array in React Js

Here is an example of a state: const initialFieldValue={ ............... photos:[] ......... } const [state, setState] = useState(initialFieldValue); Next, objects are added one by one using the onClick function like this: const handlePush=()=>{ ...

jQuery Waypoints Error: The sticky functionality is missing and cannot be utilized in this context

Trying to anchor an element at the top of a WordPress page using the jQuery Waypoints plugin. <script src="path/to/waypoints.min.js"></script> <script> $('#myelement').waypoint('sticky'); </script> However, t ...

Steps to extract data from a table with identical class names and combine them:1. Identify the table

I have created a table showcasing team names and scores. To view the demo, you can check it out here Upon clicking the Submit button, only the output of one match is displayed (Team A and B), excluding the other matches. Given that they all share the sam ...

Handsontable's unique text editor feature is encountering a tricky issue with copying and pasting

In my table, there are two columns: name and code. I have developed a simple custom editor for the code column, where the user can double click on a cell to open a custom dialog with a code editor. You can view a simplified example of this functionality he ...

An issue with SwiftUI causing images to briefly flash during animations

Encountering a perplexing issue in SwiftUI where Images on a simple VStack card flash during interaction. Check out the video demonstration linked below: Short video demonstrating the problem This particular challenge has been isolated from the larger ap ...

In JavaScript, the return statement is used to halt the execution of any subsequent statements

I encountered a situation where I need to stop the execution of the next function call if the previous function has a return statement. However, I noticed that even though there is a return statement in the "b" function below, the next function call still ...

Make sure to confirm the input length and utilize bootstrap validation for error checking

I have a rather straightforward question. I am currently utilizing Bootstrap 4.6 and am looking to implement form validation for my input field. The requirement is to validate whether the input has a length of 5 characters or less, in which case it should ...

"Narrow down the object's properties based on an array of specified property

So here's the situation: I have an object that looks like this var obj = { name1: somevalue1, name2: somevalue2, name3: somevalue3} Followed by an array var arr = [name2, name3] Both of these are dynamically generated. What I need to do is filte ...

Maximizing the potential of JavaScript by utilizing effective tags

Looking to enhance my JavaScript code by adding a maximum tags option limited to 6 with no duplicates. Check out the current snippet below: <div id="tags"> <span>php</span> <span>c++< ...