Running JavaScript within Objective-C in a Cordova plugin

I'm working with cordova version 6.5.0 and I'm trying to develop a plugin that can execute some javascript code.

I've read on various forums that I can use stringByEvaluatingJavascriptFromString method in my webview, but it seems like it's not recognized as a valid method.

As a test, I tried the following code snippet in my AppDelegate.m file:

[self.viewController.webView stringByEvaluatingJavascriptFromString:@"alert('Test')"];

However, I'm getting an error saying "No visible @interface for 'UIView' declares the selector 'stringByEvaluatingJavascriptFromString'".

In order to solve this issue, I created a new class named Utils.m:

@implementation Utils: NSObject

id webview;
id delegate;

-(void)initialise:(id)wbview Delegate:(id)dlg {

    webview = wbview;
    delegate = dlg;

}

-(void)executeJavascript:(NSString *)str {

    [delegate runInBackground:^{
        [delegate stringByEvaluatingJavaScriptFromString:@"alert('test')"];
    }];

}

Then, within my cordova plugin's pluginInitialize method, I have:

- (void)pluginInitialize {

    utils = [[Utils alloc] init];
    [utils initialise:self.webView Delegate:self.commandDelegate];
    [utils executeJavascript:@"alert('Test');"];

}

Even though the stringByEvaluatingJavascriptFromString method seems to be accepted now, the application still crashes...

Any advice or suggestions would be greatly appreciated.

Thanks, Symeon

Answer №1

When executing JavaScript code within an app, always opt for using the evalJs method over the

stringByEvaluatingJavaScriptFromString
method:

[handler evalJs:@"alert('sample')"];

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

Having trouble downloading the compression webpack plugin using npm, as it keeps throwing an error

Hey there, this message pops up when attempting to execute the following command: npm install compression-webpack-plugin Here is the accompanying error: `PS D:\phaser games\game-slot-machine> npm install compression-webpack-plugin npm ERR! ...

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...

Creating a personalized contact form with a mailto link that also includes the ability to automatically copy information into the email

I'm in the process of developing a basic contact form that includes input fields for name and subject, as well as a send button (which is an <a> element inside a <div>. I am utilizing an <a> tag because I intend to use mailto functio ...

Increase the value of X within the given string

I am working on developing an application that transforms the initial string: 1.2.3.X Into multiple strings: 1.2.3.0 1.2.3.1 1.2.3.2 1.2.3.3 1.2.3.4 ...... This is a snippet of the code I have written so far: String.prototype.count=function(c ...

Steps for freeing up a JSONConnection object1. To start the

Currently, I am utilizing a JSONConnection object in the following manner. - (void)startGettingSearchResultsByKeyword:(NSString *)keyword delegate:(id <DataProviderDelegate>)delegate { /* Prepare request */ JS ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Transform your CSS styles into Material-UI makestyles

I am looking to implement an IconButton with a website preview feature that appears when the user hovers over the help icon. I came across a similar solution using CSS, but I need to convert it to Material UI. Here is the CSS code that needs to be converte ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

What causes the closure variable to be reset after iterating over JSON data using $.each method?

Take a look at this scenario: var elements = []; $.getJSON(data_url, function(result) { $.each(result, function(key, value) { elements.push(parser.read(value.data)); // at this point, "elements" contains items }); }); dataLayer.addElements( ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Is there a way to extract a specific element from an array stored within a form element's value?

I am encountering an issue with retrieving values from an array in an HTML form element using jQuery. Despite my efforts to explain and provide code, I am not getting the desired results. Can someone help me understand what is going wrong in my code? Thank ...

The function of window.location is not responsive when used in conjunction with an ajax

The main page redirect occurs in 2 scenarios: When the user clicks logout When the session expires Code for logout functionality: $("#logoutLink").click(Logout); function Logout() { $.post("Logout", { antiCSRF: '{{acsrf}}&apo ...

Automatically focus on input when scrolling reaches a specific element using jQuery

I have been utilizing a jQuery plugin called Waypoints to handle scroll actions. My goal is to focus on the first input element of a section that is currently visible on the screen and then shift the focus to the input of the next respective sections as t ...

Enhance the Material UI StepIcon by embedding real icons within the background circle

I have scoured through stack overflow but haven't come across a specific question addressing my issue. I am working on styling a Material UI Stepper component in a unique way. Most examples I've found use withStyles or makeStyles for color custom ...

Tips for troubleshooting syntax errors in JavaScript

Are there any online tools similar to jsfiddle where I can input my JavaScript code and receive feedback on syntax errors, misplaced commas, or semicolons? Here is the example code I am looking to validate: $("#customer").autocomplete({ ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

A method for retrieving the variables from the initial API function for use in a subsequent API function

$.getJSON(url, function (data) { $.getJSON(url_wind, function (data2) { //perform actions with 'data' and 'data2' }); }); While attempting to use the data from the initial getJSON() call in the second getJSON() call ...