简体   繁体   中英

How to execute a Javascript function inside WKWebview?

Hello community,

I am stuck with this problem for days and I couldn't find any solutions, maybe you can help me out..

I created an App that uses the WKWebview to connect to a website. The login happens native on iOS, after the user issued their credentials, i want to Login on the webpage as well.

Therefore my Webpage has a Javascript function called "handleLogin" where i receive the credentials and the user does not have to login again and is directly fowarded to his main page.

Now I want to call handleLogin() from native code inside my WKWebview.

I already tried several ways, on Android it can easily be done with:

view.LoadUrl("javascript:(handleLogin(placeholder))");

In iOS I already tried it inside
public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation) with:

await webView.EvaluateJavaScriptAsync("handleLogin(credentialsPlaceholder);");

but the only result i get is an exception:

Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=0, WKJavaScriptExceptionMessage=TypeError: undefined is not a function, WKJavaScriptExceptionColumnNumber=0, NSLocalizedDescription=A JavaScript exception occurred}'

Can it be that I have to wait longer until everything is loaded?
I am sure that handleLogin exists, testet it on Android as well as in browsers, how can it be undefined?
Does EvaluateJavascript work only on internal scripts?

I hope you can help me out, Kind regards

Found some information that might help

source: read more

User Scripts

The WKUserScript object, when added to the userContentController, allows developers to take JavaScript and inject it into a webpage. Here's a simple example of adding a script to change the background color of the Google web page from above:

let contentController = WKUserContentController()
let scriptSource = "document.body.style.backgroundColor = `red`;"
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM