Extract the HTML content from the existing UIWebview

My UIWebview displays links that, when clicked, send JSON data. To show this data, I need to:

1) Detect when a link is clicked

2) Retrieve the JSON

To retrieve the JSON, I tried using

[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
which resulted in:

<pre style="word-wrap: break-word; white-space: pre-wrap;">{some JSON}</pre>

Unfortunately,

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")"];
returned an empty object. Are there any other methods to retrieve my JSON?

Regarding detecting when a link is clicked (question 1), is there a UIWebView delegate method available for this purpose?

Answer №1

Encountered a similar issue and managed to resolve it using the following code snippet:

    NSString *jsonString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName(\"pre\")[0].innerHTML"];

Answer №2

When it comes to iOS development, the iOS Developer Library is a valuable resource. It turns out that UIWebView offers a protocol that developers can subscribe to for delegate callbacks. If you're interested in learning more about these delegate callbacks, check this link out: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIWebViewDelegate

One of the important method from this protocol is:

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

By implementing this protocol method, you can access the NSURLRequest object and extract information like the URL, allowing you to further customize your app's functionality.

Additionally, consider using the - (NSData *)HTTPBody instance method on NSURLRequest objects to retrieve JSON data. You can then utilize NSJSONSerialization from the Foundation framework to convert this data into NSObject instances. Here's a sample code snippet to get you started:

// UIWebView delegate method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSData *jsonData = request.HTTPBody;
  id jsonObj = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: nil];
  // perform actions with the retrieved object...
  
  return NO; // prevent the webview from loading the raw json data
  
}

Keep in mind that this code assumes pure JSON data. If there are HTML elements mixed in with the JSON, you may need to implement a mechanism to filter out the HTML content. For more detailed information on NSJSONSerialization, refer to the official documentation: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

Happy coding!

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

Disabling the camera feed in a React application

Attempting to turn off the webcam using javaScript in React has been a bit challenging. Whenever I shift to a new component or when a component is destroyed, my react component immediately moves to the next page, but the webcam light remains on in the new ...

Is it beneficial to establish a universal ng-app scope within an AngularJS application that functions as a multi-page app?

Just dipping my toes into AngularJS waters, and this question will surely prove that. We're in the midst of revamping an existing app to take advantage of AngularJS for CRUD operations and more. Rather than starting from scratch, we've decided a ...

Text that serves as a temporary substitute within the <p> element

I attempted to include a placeholder in the <p> tag, but my approach didn't yield the desired result. I'm looking to have a placeholder within the <p> tag that can be substituted with the input text value. Link to JS fiddle $( ...

What steps should I take to resolve the issue with the error message: "BREAKING CHANGE: webpack < 5 previously included polyfills for node.js core modules by default"?

When attempting to create a react app, I encounter an issue every time I run npm start. The message I receive is as follows: Module not found: Error: Can't resolve 'buffer' in '/Users/abdus/Documents/GitHub/keywords-tracker/node_modul ...

Tips for enabling autoplay for videos in Owl Carousel

I am facing an issue with implementing autoplay functionality for videos in an owl carousel. Despite trying different solutions found online, including this Owl Carousel VIDEO Autoplay doesn’t work, I haven't been able to make it work. Additionally, ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

Add a JavaScript file into a PHP document

I've been searching for a solution in various forums, but the main answer I found doesn't seem to work for me. As someone new to Web development, I'm attempting to create a simple JavaScript program that takes a JSON string of products and ...

Merging various variables together where applicable in JavaScript

I am looking to combine different variables if they exist and return the result. However, I need to separate the values with "-" and only return the variables with a value. Here is my code: var test = ""; var test1 = ""; var test2 = ""; var test3 = ""; ...

Design shortcuts for the home screen that do not require opening the app

I am looking for a solution for my iOS 9 app with home screen quick actions. I want the quick action to be able to schedule reminders without opening the app. Is there a way to achieve this functionality? ...

Pairing tags and text within jQuery

Can jQuery be used to match a string along with its enclosing tags? I am looking to identify the following… <p>Oops! We could not locate your form.</p> and either replace it or apply a specific class - I haven't decided yet. While I c ...

Are npm modules trustworthy, and how can we ascertain their reliability?

As I utilize numerous Node.js modules via the npm package manager, a concern arises regarding their trustworthiness due to the fact that they are not created by reputable organizations. I am unsure if the npm team conducts security checks on every module ...

An error occurred due to incorrect syntax in the URI value following the serialization of JSON

When making a REST web service call using PUT, I need to send JSON in a specific format: {"leader":"John Smith","leader_id":"asldfkj234234324asldkfs234","resource_uri":"/api/event/38001"} However, the serialized JSON includes extra '\' cha ...

remove all clicks from jQuery queue

I am facing an issue with a click event that triggers other click events, resulting in the addition of elements to the DOM. EDIT: However, upon clicking it multiple times, additional elements are added each time. Checking the jQuery queue confirms that an ...

Puppeteer: Easily choosing a dropdown selection by its displayed text

When using Puppeteer, you have the ability to choose an option from a dropdown by specifying the value as a parameter: page.select('select#idOfSelect', 'optionValue'); I'm wondering if there is a way to select an option by its te ...

What steps can I take to restrict a draggable element to the body, prevent text selection, and allow form inputs to be enabled?

I'm currently utilizing the react-draggable library for my project. In order to ensure that the element remains within the confines of the body element, prevent text selection, and allow interaction with form inputs inside the draggable element, I en ...

Ensuring the integrity of object formats in vue.js

Currently, I am working on a component using vue.js and facing a slight issue. The component has a wide range of parameters, so to keep things organized, I opted for the approach outlined below: <script type="text/javascript"> Vue.$noClientConf ...

Chromium is having issues with updating the dynamic source attribute

One portion of my script that pertains to the question is as follows: <script type="text/javascript> function handleImageClick() { var image = $("#image_id"); $(image).attr("src", "ajax-loader.gif"); $.ajax({ ...

Core data queries

As I embark on developing my core data database, I find myself facing some perplexing questions that I hope someone can help me unravel. Could you please provide a simplified explanation? 1) NSManagedObject *employee=[NSEntityDescription insertNewObject ...

Utilizing React Refs to Retrieve Value from HTML Select Element

I am currently working on a form that includes the use of an HTML select element. <select className="form-control" id="ntype" required > <option value = "">None</option> <option value = "1">1</option> < ...

Using Google scripts for sending POST requests with HTMLRequest

I am attempting to authenticate my account for DirectEnergie using Google App Script. When I make the request on POSTMAN with Chrome, it works perfectly fine. However, when I try to run the same script as shown below, it simply returns the HTML of the firs ...