Inject a Local JavaScript into Uiwebview

Inject a local javascript into UIWebView

The following code will inject javascript locally

- (void)injectJavascript:(NSString *)resource {
NSString *jsPath = [[NSBundle mainBundle] pathForResource:resource ofType:@"js"];
NSString *js = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];

[self.webView stringByEvaluatingJavaScriptFromString:js];
}

Just pass in the name of the file before the js, eg.

[self injectJavascript:@"script"];

To do inject javascript from your server you can download it first and load it into the web view in a similar manner.

Load local javascript in webview?

Using WKWebView for javascript method call:

Step 1. Import class for webkit

Obj-C: #import <WebKit/WebKit.h>
Swift: import WebKit

Step 2. Create a WKWebView instance (Unfortunately it can only be done programatically)

Obj-C @property (strong, nonatomic) WKWebView *wkWebView;

Swift var wkWebView: WKWebView? = WKWebView()

Step 3. Then in viewDidLoad

Obj-C:

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

NSString *scriptSourceCode = @"your javascript code here";
WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];

WKUserContentController *controller = [[WKUserContentController alloc] init];
[controller addUserScript:script];

configuration.userContentController = controller;

_wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

[self.view addSubview:_wkWebView];

Swift:

    let configuration = WKWebViewConfiguration()
let controller = WKUserContentController()

let scriptSourceCode = "your javascript code here"
let script = WKUserScript(source: scriptSourceCode, injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true)
controller.addUserScript(script)

configuration.userContentController = controller

self.wkWebView = WKWebView(frame: self.view.frame, configuration: configuration)

self.view.addSubview(self.wkWebView!)

Step 4 Load a HTML string (or a loadRequest) in the wkWebView:

Obj-C:

[_wkWebView loadHTMLString:_desiredHTML baseURL:[[NSBundle mainBundle] bundleURL]];

Swift:

self.wkWebView?.loadHTMLString(_desiredHTML, baseURL: NSBundle.mainBundle().bundleURL)

Step 5. Call a method which exists in the javascript included in the WKWebView

Obj-C:

    NSString *callMethod = [NSString stringWithFormat:@"existingMethodWithParam(%@)", stringParam];

[_wkWebView evaluateJavaScript:callMethod
completionHandler:^(id obj, NSError *error) {

if (error)
{
NSLog(@"ERROR evaluating JavaScript - %@", error);
}
else
{
NSLog(@"Returned value - %@", obj); //if the javascript method has a return type
}
}];

Swift:

    let callMethod = String(format: "existingMethodWithParam(%@)", stringParam)

[self.wkWebView?.evaluateJavaScript(callMethod, completionHandler: { (obj, error) -> Void in

println(obj)
println(error)
})]

Injecting JavaScript into UIWebView

Probably you'll have to wait for the request to finish before you can use stringByEvaluatingJavaScriptFromString. Set wv.delegate = self; and then implement -webViewDidFinishLoad like this

-(void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"document.write('This Works')"];
}

Inject Javascript into Webview - Swift

Just do:

let js = "var myelement = document.getElementById(\"test\");myelement.innerHTML= \"New Text\";"
webView.evaluateJavaScript(js, completionHandler: nil)

If you are using UIWebView instead of WKWebView, do this:

let js = "var myelement = document.getElementById(\"test\");myelement.innerHTML= \"New Text\";"
_ = webView.stringByEvaluatingJavaScript(from: js)

UIWebView CSS injection using JavaScript

To inject javascript into a web view you must explicitly write in the html.

An example of this is here where I wrote in a javascript scrollTo function:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function myFunction() { "
"window.scrollTo(100,100)"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];

[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];}

This code writes the entire script tags and the myFunction into the head of the HTML

Override a remote HTML with a local Javascript file in UiWebView?

We found a solution. Rather then attempting to inject a local file we came across this solution where the app scans the site for remote reference like "url.com/style.css" and substitute it with a local file.



Related Topics



Leave a reply



Submit