The stringByEvaluatingJavaScriptFromString method is essentially ineffective

Currently, I am utilizing goNative.io to execute my web application within a wrapper/native iOS app. In order to enhance the functionality, I have incorporated some additional objective-c code that is responsible for extracting and storing data from HTML5 local storage when the app is closed, and then reinserting that data back into the local storage upon reopening.

The main issue I am facing is that the method

stringByEvaluatingJavaScriptFromString:jsString
does not appear to be executing any JavaScript code within my app. Even simple commands such as alert or console.log do not produce any outcomes in UIWebView, without any error messages appearing either.

Any suggestions on how to resolve this?

appDelegate.h

#import <UIKit/UIKit.h>
#import <OneSignal/OneSignal.h>
#import "LEANWebViewController.h"
#import "LEANCastController.h"
#import "Reachability.h"

@interface LEANAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property LEANCastController *castController;
@property NSURLRequest *currentRequest;
@property Reachability *internetReachability;
@property (strong, nonatomic) OneSignal *oneSignal;
@property UIWebView *webView;

- (void)configureApplication;

@end

appDelegate.m

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //Persist local storage data
    NSLog(@"Reading local storage since app is becoming active");

    //Attempting to run Javascript upon app opening.. but no result!
    NSString *jsString = @"alert('Javascript wont run!!! Can't read local storage');";
    [self.webView stringByEvaluatingJavaScriptFromString:jsString];
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Triggered when the application is transitioning from active to inactive state, like during incoming calls or when the user closes the app.
    // This method can be used to pause ongoing tasks, stop timers, and limit OpenGL ES frame rates. Games typically use it to halt game activity.

    //Persist local storage data
    NSLog(@"Persisting local storage since app will resign active");

    //Extracting an item from local storage
    NSString *jsString = @"localStorage.getItem('mpo.subdomain');";
    NSString *someKeyValue = [self.webView stringByEvaluatingJavaScriptFromString:jsString];
    NSLog(@"**** localStorage subdomain string: %@", someKeyValue);

    // Storing the obtained subdomain in a persistent iOS variable for future use in the app
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    [userdefault setObject:someKeyValue forKey:@"subdomain"];
    [userdefault synchronize];

    //Utilizing User defaults
    NSLog(@"NSUserDefaults Subdomain %@",[userdefault valueForKey:@"subdomain"]);
}

Answer №1

For the stringByEvaluatingJavaScriptFromString method to work properly, the app must execute its web view delegate method "webViewDidFinishLoad". Otherwise, the self.webview value will remain nil.

You can try implementing the following method:

  • (void)webViewDidFinishLoad:(UIWebView*)theWebView {

[theWebView stringByEvaluatingJavaScriptFromString:@"console.log('webViewDidFinishLoad');"];

}

Additionally, ensure that your "self.webview" is not nil before using the method.

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

Integrating image transitions into JavaScript

Could you provide guidance on how to create buttons from the three images within the "fadein" div in order to navigate directly to a specific jpeg? Currently, the three jpgs are displayed in a continuous loop. Thank you. ...

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

How can I retrieve the initial truthy value in JavaScript/NextJS for assigning to a property?

Within my NextJS project developed with JavaScript, I am seeking a way to assign a value to a property on a local object dynamically. const localItem = { name: <<value to be set goes here>> }; Handling the data used for setting the property ...

Retrieve data from AJAX request using array index

A certain script in my possession is able to extract data from a JSON file and store the name property of each element in an array. HTML <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script> var names = []; var f ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...

Exploring the world of jQuery sliders and dynamically updating div container content

Alright, here's what I have come up with so far: First, take a look at this website to see the idea I am trying to explain: What I am aiming for is this concept: A visitor goes to the provided website and wants to know what type of sandwich they can ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Ensure props are properly sanitized in Vue 3 before utilizing them

How can I efficiently clean up props in Vue 3 before using them? I am faced with the challenge of handling props that can be either objects or stringified JSON versions of those objects. Currently, the application I'm working on tackles this issue by ...

Is the xmlhttprequest timeout/abort feature not functioning as anticipated?

Check out this snippet of my AJAX function: /** * This function initiates an AJAX request * * @param url The URL to call (located in the /ajax/ directory) * @param data The data to send (will be serialized with JSON) * @param callback The fu ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Having trouble with jQuery variable assignments not working in Safari?

My jQuery 1.3.2 code is encountering issues with Safari 4 for reasons unknown to me. Even though all my javascript references are placed right before the closing <body> tag, I am facing difficulties with the following snippet: var status = $(' ...

Turn off the ability to view the content of .css and .js files within the browser

Earlier, I inquired about how to disable file and folder listing and discovered that it can be achieved using a file named .htaccess. To disable folder listing, I entered Options -Indexes in the .htaccess file located in the parent folder. Additionally, to ...

add the elements of an array to multiple div elements sequentially

I'm attempting to update all titles in .item with the values from array. The array I am using contains the following elements: var itCats = ['one', 'two', 'three', 'four']; Additionally, this is the HTML struc ...

Calculate the total price using jQuery

I’m a beginner in JavaScript and I’ve hit a roadblock. I have a plus and minus button that adds up product quantities, but I need the total price to reflect this as well. Some products can only be purchased in multiples of 2, 5 or 10. Here is the HTML ...

Stock Chart that resembles the functionality of Google's popular line chart feature

Can anyone recommend a Javascript or SVG chart library that has a style similar to a Google Chart? I have been searching without much luck and would appreciate some guidance on how to achieve a similar look. I've looked into the Google Visualization ...

How to Efficiently Organize OpenAI AI Responses Using TypeScript/JavaScript and CSS

I'm using a Next.js framework to connect to the OpenAI API, and I've integrated it seamlessly with an AI npm package. The functionality is incredible, but I've encountered an issue regarding line breaks in the responses. You can find the AI ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

Guide on accessing a method from a div element in VueJS

Is there a way to only render a div based on a specific condition and call a method when the condition is true? Here's an example of what I'm trying to achieve: <div v-if="timetable === null" @click="mymethodhere"> ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...