iOS Uiwebview JavaScript - Insert Data -Receive Callbacks

iOS UIWebView Javascript - insert data -receive callbacks?

You can call a javascript method and pass the value by using this

NSString *selectedValue = [webViewInstance stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getAndReturnRadioValue(%d)", questionCounterIntValue]];

But to trigger back from javascript you need to use a workaround method,

Implement the following webViewDelegate method

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

NSLog(@"passed data from web view : %@",[[request URL] query]);

if([[[request URL] query] isEqualToString:@"clickedOnLineNo"])
//Do your action here

You have to navigate to a fake URL from your javascript method like,

window.location = "someLink://yourApp/form_Submitted:param1:param2:param3";

on a button click or your required action.

You could take a look at my answer for this question
Submit a form in UIWebView

Appending UIWebView

- (void)addToWebView:(NSString *)toAdd {
NSString *java = [NSString stringWithFormat:@"document.body.innerHTML += '%@'", toAdd];
[classWebView stringByEvaluatingJavaScriptFromString:java];

(Make sure toAdd doesn't contain any unescaped ' character)

Submit a form in UIWebView

You can use the


function for firing a javascript method from objective c and get a return value from that method.

For example

//Calling the getTheUsername in the javascript.
NSString *userName = [yourWebView stringByEvaluatingJavaScriptFromString:@"getTheUsername()"];

and in javascript

//Method in javascript
function getTheUsername()
return userNameVariable;

And I doubt that here you may wanna do vice-versa (Call obj-c method from javascript). This cannot be done directly here is the work around.

Set a UIWebViewDelegate, and implement the method webView:shouldStartLoadWithRequest:navigationType:. In your JavaScript code, navigate to some fake URL that encodes the information you want to pass to your app, like, say:
window.location = "someLink://yourApp/form_Submitted:param1:param2:param3";
In your delegate method, look for these fake URLs, extract the information you need, take whatever action is appropriate, and return NO to cancel the navigation.

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

NSLog(@"%@",[[request URL] query]);

return YES;

return array from javascript function to objective-c xcode

You have to use webview's

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

delegate method. See my answer here.

iOS UIWebView Javascript - insert data -receive callbacks?


and this one,

Submit a form in UIWebView

Code Snippet to use complex JavaScript to insert HTML inside UIWebView?

To load some file form inside UIWebView, do the following

<script language="javascript" type="text/javascript">
var bundlePath = "here_goes_full_path_to_your_bundle";
// It should be something like file:///var/.../
// Set it from your code

jQuery.get(bundlePath + "/someFile.html", function(data) {alert(data);});

How can I reliably detect a link click in UIWebView?

So far I have arrived at the following solution. First, I inject some JS code into the page when loaded:

function reportBackToObjectiveC(string)
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "callback://" + string);
iframe = null;

var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
links[i].addEventListener("click", function() {
}, true);

When user taps a link, I know it in advance thanks to the webView:shouldStartLoadWithRequest: navigationType: delegate call:

if ([[[request URL] scheme] isEqualToString:@"callback"]) {
[self setNavigationLeavingCurrentPage:YES];
return NO;

Then if another request comes and _navigationLeavingCurrentPage is true, I know the user has clicked a link even though the navigation type flag is UIWebViewNavigationTypeOther. I still have to test the solution extensively, for I’m afraid that it will lead to some false positives.

Using anchor tag with UIwebview?

[webview stringByEvaluatingJavaScriptFromString:@"window.location.hash = '2002'"];

How to inject JavaScript callback to detect onclick event, using iOS WKWebView?

User Scripts are JS that you inject into your web page at either the start of the document load or after the document is done loading. User scripts are extremely powerful because they allow client-side customization of web page, allow injection of event listeners and can even be used to inject scripts that can in turn call back into the Native app. The following code snippet creates a user script that is injected at end of document load. The user script is added to the WKUserContentController instance that is a property on the WKWebViewConfiguration object.

// Create WKWebViewConfiguration instance
var webCfg:WKWebViewConfiguration = WKWebViewConfiguration()

// Setup WKUserContentController instance for injecting user script
var userController:WKUserContentController = WKUserContentController()

// Get script that's to be injected into the document
let js:String = buttonClickEventTriggeredScriptToAddToDocument()

// Specify when and where and what user script needs to be injected into the web document
var userScript:WKUserScript = WKUserScript(source: js,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: false)

// Add the user script to the WKUserContentController instance

// Configure the WKWebViewConfiguration instance with the WKUserContentController
webCfg.userContentController = userController;

Your web page can post messages to your native app via the window.webkit.messageHandlers.<name>.postMessage (<message body>) method.
Here, “name” is the name of the message being posted back. The JS can post back any JS object as message body and the JS object would be automatically mapped to corresponding Swift native object.
The following JS code snippet posts back a message when a button click event occurs on a button with Id “ClickMeButton”.

var button = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
varmessageToPost = {'ButtonId':'clickMeButton'};

In order to receive messages posted by your web page, your native app needs to implement the WKScriptMessageHandler protocol.
The protocol defines a single required method. The WKScriptMessage instance returned in the callback can be queried for details on the message being posted back.

func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {

if let messageBody:NSDictionary= message.body as? NSDictionary{
// Do stuff with messageBody


Finally, the native class that implements WKScriptMessageHandler protocol needs to register itself as a message handler with the WKWebView as follows:

// Add a script message handler for receiving  "buttonClicked" event notifications posted 
// from the JS document
userController.addScriptMessageHandler(self, name: "buttonClicked")

Detecting UIWebView finish to play youtube video on iPad

No, there's no way to directly get web page event from UIWebView. But we can accomplish this by using Javascript.

  • First you use embed Javascript in your custom HTML, to detect video ending play event.
  • Then you try to load a scheme-customized request using JavaScript, and UIWebView could catch the request.

These links may help:

  1. Calling Objective-C from JavaScript in an iPhone UIWebView

  2. Javascript callback in Objective-C

  3. YouTube iFrame API

updated with an example:

in UIWebView's delegate, i put:

#pragma - mark WebView Delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

if ( [[[request URL] scheme] isEqualToString:@"callback"] ) {

NSLog(@"get callback");

return NO;

return YES;


the web page is load when viewDidLoad:

[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle       mainBundle] pathForResource:@"youtube" ofType:@"html" ]]]];

and in youtube.html i put:

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>


// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {;

// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {

if ( == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
if ( == YT.PlayerState.ENDED) {
window.location = "callback:anything"; //here's the key
function stopVideo() {

you can see i add

if ( == YT.PlayerState.ENDED) {
window.location = "callback:anything";

to YouTube's iFrame API demo, and it catches the player end playing event and try to load a request with scheme "callback", then the UIWebView Delegate could catch it.

You can use this method to trigger any event using JavaScript;

Related Topics

Leave a reply