Inject a JavaScript Code in Webview iOS

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)

Swift Inject Javascript to remove HTML element into WebView

First, your javascript code will never work because you are trying to retrieve the element with id mobile-promo, but instead the tag name of your element is mobile-promo. (and it doesn't have id attribute)

If there is only one HTML element with mobile-promo as tag, then the following javascript code will work:

function removeDummy() {
var elem = document.getElementsByTagName('mobile-promo')[0];
elem.parentNode.removeChild(elem);
return false;
}
removeDummy()

If not then you should do something like this:

function removeDummy() {
var elem = document.getElementsByTagName('mobile-promo');
for (var i = 0; i < elem.length; i++) {
if (elem[i].getAttribute("jsname") == "EfADOe" && elem[i].getAttribute("jscontroller") == "sqHuef" && elem[i].getAttribute("jsaction") == "rcuQ6b:npT2md") {
elem[i].parentNode.removeChild(elem[i]);
}
}
return false;
}
removeDummy()

To inject your javascript code, there is WKUserScript API available from iOS 8. You can do something like this at viewDidLoad:

override func viewDidLoad() {
super.viewDidLoad()

let source = """
function removeDummy() {
var elem = document.getElementsByTagName('mobile-promo')[0];
elem.parentNode.removeChild(elem);
return false;
}
removeDummy()
"""
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
webView.configuration.userContentController.addUserScript(script)
}

Note that just to be safe, we passing .atDocumentEnd as injectionTime parameter. As documentation states:

Inject the script after the document finishes loading, but before
other subresources finish loading.

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)
})]

How to inject javascript file to html string coming from api?

You can use WKUserScript and append the javascript to webview using the WKWebViewConfiguration.

let contentController = WKUserContentController()
guard let scriptPath = Bundle.main.path(forResource: "script", ofType: "js"),
let scriptSource = try? String(contentsOfFile: scriptPath) else { return }
let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(script)
let config = WKWebViewConfiguration()
config.userContentController = contentController

let webView = WKWebView(frame: .zero, configuration: config)
self.view.addSubview(webView)

webView.loadHTMLString(htmlString, baseURL: nil)

How to inject javascript in my UIWebview

[webView stringByEvaluatingJavaScriptFromString:@"your script"];

stringByEvaluatingJavaScriptFromString:

Returns the result of running a script.
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script Parameters

script

The script to run.

Return Value

The result of running script or nil if it fails.

Discussion

JavaScript execution time is limited to 10 seconds for each top-level
entry point. If your script executes for more than 10 seconds, the web
view stops executing the script. This is likely to occur at a random
place in your code, so unintended consequences may result. This limit
is imposed because JavaScript execution may cause the main thread to
block, so when scripts are running, the user is not able to interact
with the webpage.

JavaScript allocations are also limited to 10 MB. The web view raises
an exception if you exceed this limit on the total memory allocation
for JavaScript. Availability

Available in iOS 2.0 and later.


Related Topics



Leave a reply



Submit