Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, February 29, 2016

Rustic way to import your AngularJS configuration from an external JS file

Many times we want to store our constants/config details into a different file to simplify the deployment process or simply to organise the code.

Here you can see a very basic way to save your app's config file into a different location.

https://jsfiddle.net/sergioloppe/bvajr7bw/

The code is self-explanatory.

Hope helps





Tuesday, May 7, 2013

UIWebview. How to call javascript functions from objective-c

I wrote about this long time ago but only to remember how simple it is.

1) Write the javascript function in your HTML file

function callMePlease () {
    // Your code here
}


2) Use this line to call the function from Objective-C using your  UIWebView object.
[webview stringByEvaluatingJavaScriptFromString:@"callMePlease()"];

For example if we only want to execute some javascript code in our webview we can use:

NSInteger pos = 100;NSString* s=[[NSString alloc] initWithFormat:@"window.scrollTo(%i, 0)",pos];[webViewMenu stringByEvaluatingJavaScriptFromString:s];

If we want to call a Objective-C function from our JavaScript code... things are a little bit more difficult:

1) In Objective C we must have

- someFunctionOnInit {
    
    webView = [[UIWebView alloc] init];
    // Register the UIWebViewDelegate in order to shouldStartLoadWithRequest to be called (next function)
    webView.delegate = self;
    
}

// This function is called on all location change :
- (BOOL)webView:(UIWebView *)webView2
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    
    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {
        
        // Extract the selector name from the URL
        NSArray *components = [requestString componentsSeparatedByString:@":"];
        NSString *function = [components objectAtIndex:1];
        
        // Call the given selector
        [self performSelector:NSSelectorFromString(functionName)];
        
        // Cancel the location change
        return NO;
    }
    
    // Accept this location change
    return YES;
    
}

- (void)myObjectiveCFunction {
    
    // Do whatever you want!
    
}

There are another ways to do the same but it is enough for today. For more information check this.


Cheers