Utilizing JavaScript to populate a webview in iOS with data retrieved from Objective C

Can anyone guide me on how to populate an HTML webview with variables stored in Objective-C?

I assume I need to use the following code snippet:

[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName];

However, I am unsure about what exactly should be placed there and what my JavaScript code needs to be in order to correctly implement the passed variables.

Here is a snippet of the HTML code for context:

<ul><li><span>First Name:</span> first name goes here </li>
  <li><span>Last Name:</span> last name goes here</li>

Updated code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]];
}

-(void)viewDidAppear:(BOOL)animated
{
    NSString *str  = @"John";
    NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str];
    [self.webView stringByEvaluatingJavaScriptFromString:script];


}

Update 2: javascript/html:

<ul><li><span>Policy Number:</span>        
<script> function myFunc(str)
        {
            document.write(str)  }
        </script>

Answer №1

After exploring various options, I decided to implement a different JavaScript approach that might be beneficial to others.

Here is the code snippet:

NSString *name  = @"John";
NSString *scriptCode = [NSString stringWithFormat:@"document.getElementById('name').innerHTML = '%@';", name];
[self.webView stringByEvaluatingJavaScriptFromString:scriptCode];

JavaScript snippet:

<li><span>Name:</span>   <span id = 'name'>name goes here</span>
      </li>

Answer №2

To include data in an HTML string using JavaScript, you must first create a JavaScript function that will handle the addition of the data. Once this function is set up, passing the data to it becomes a simple task.

NSString *script = [NSString stringWithFormat:@"addDataToHTML([%@])", data]
[self.webView stringByEvaluatingJavaScriptFromString:script];

Adding data to an HTML string with JavaScript can be done effortlessly, as demonstrated here.

Answer №3

Are you able to manipulate the raw HTML code directly within your application? If so, have you considered implementing something similar to this?

WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webview];
NSString *htmlString = [NSString stringWithFormat:@"<html>\
<ul><li><span>First Name:</span> %@</li>\
<li><span>Last Name:</span> %@</li>\
</html>", @"Jane", @"Doe"];
[webview loadHTMLString:htmlString baseURL:nil];

If incorporating JavaScript is of interest, consider checking out this resource for guidance: How to control UIWebView's javascript

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

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Detect Empty Fields as Invalid in Angular 2+ Form Validation

I have been implementing Form Validations in my form using reactive form validation. However, I encountered a challenge when checking a field that is touched and dirty. For example: HTML: <input id="name" class="form-control" formControlName="n ...

Retrieving information from an HTML table?

Is it considered poor practice to transmit data to a back-end application without the presence of an html <form> or any <input> elements? In my current scenario, there is a need to retrieve information from an html page, transfer it to a back- ...

Develop a Python mechanism for locking and unlocking in asynchronous mode

I've come up with a new_lock function in JS that helps to avoid callback hell: function new_lock(){ var unlock,lock = new Promise((res,rej)=>{ unlock=res; }); return [lock,unlock]; } var [lock,unlock] = new_lock(); call_some_func_with_call ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Can you describe the characteristics of emissive materials in three.js?

Currently, I'm delving into a basic demo using three.js and finding myself perplexed by the way THREE.MeshPhongMaterial behaves, especially since I come from a background working with the Unity Game Engine. create_ring() { // creates a ring mesh ...

Building Ext JS packages is an essential step in the development

Sencha command offers a seamless way to create, build, and distribute custom packages. The Ext JS library itself is constructed using Sencha command. I am curious about the process for ensuring that the built package maintains proper order, especially whe ...

What is the best way to establish a maximum value for variable inputs?

In my Vue form, I have dynamic inputs for issuing shares to shareholders. The user first registers the total amount of shares in the form, then starts issuing this total amount partially by adding dynamic inputs as needed. Finally, the form is submitted. M ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Error: The variableRegex is unable to execute the object foundTranslation, producing a TypeError in the replaceDynamicString function

While experimenting with a UIkit react app, I decided to modify some text on the front end website and encountered this error message. Could it be that the issue lies in the fact that the specific text in question does not have a corresponding translation ...

Creating unit tests without relying on a testing framework: A guide

My goal is to unit test a simple function using pure JavaScript: NS.isType = function (type, obj) { if (obj.constructor && obj.constructor.name) { return obj.constructor.name === type; } return toString.call(obj) === '[obj ...

React components experiencing conflicts when using shorthand inline styles that overwrite one another

Within my React component, I am receiving a values object with attributes like: {gridColumn: '1 / 3', gridRow: '2 / 5', gridArea: 'header'} I apply these values to the component's style as follows: this.cell.style.setP ...

What is the correct way to define a variable in Jade?

My app functionality includes exporting user information once they are signed in, allowing the router to update the profile template. However, I am looking to enhance this by dynamically rendering different navigation bars based on the user's sign-in ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Issue with inconsistency in TypeScript when updating image sources within Promise.all

Currently, in my SPFx webpart using React/TypeScript, I am facing a challenge with replacing the source of some images. The initial source needs to be fetched first via another Microsoft Graph API call before being replaced. My approach involves fetching ...

What is the best way to resize an SVG to perfectly fit the parent div container?

I need to display multiple SVGs from various sources, each with different height, width, and viewbox. I want them all to render within a fixed height and width div, filling up the available space. How can I scale these SVGs to fit the container div? For i ...

Deciphering the GWT compiler's results

Although I'm not a JavaScript developer, I'm currently delving into the process of converting Java code to JS using the GWT compiler in order to identify the root cause of memory growth in our extensive application. Every now and then, I come ac ...