[英]How to pass Objective-C value to JavaScript
Now I would like to pass an Objective-C object (String) to JavaScript (in WKWebView).现在我想将 Objective-C object(字符串)传递给 JavaScript(在 WKWebView 中)。
Want to load an Objective-C variable into JavaScript at the timing when window.onload
is executed, as shown below.想在执行 window.onload 的时机将
window.onload
变量加载到 JavaScript 中,如下所示。
var objcString = "";
window.onload = function() {
objcString = objc.getObjcString();
execXxxWhenWindowOnload(objcString);
}
How can I implement Objective-C function?如何实现 Objective-C function?
you can use evaluateJavaScript function for passing value.您可以使用 evaluateJavaScript function 来传递值。 Here is an example of it please check
这是一个例子,请检查
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSString *strFunction = [NSString stringWithFormat:@"'function name'('%@')",'value'];
[self.webview evaluateJavaScript:strFunction completionHandler:nil];
}
Assuming:假设:
you could consider using a query param (albeit be wary not to clash with some existing query param names in the url).您可以考虑使用查询参数(尽管要小心不要与 url 中的一些现有查询参数名称发生冲突)。
NSString *yourCustomString = @"value";
NSString *urlString = [NSString stringWithFormat:@"https://www.yourserver.com?myParam=%@", yourCustomString];
[self.webView loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:urlString]]];
In the js counterpart you'd handle that like this:在对应的 js 中,您可以这样处理:
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
execXxxWhenWindowOnload(myParam);
}
I haven't found a way to inject custom js before window.onload
using WKUserScript
/ WKUserScriptInjectionTimeAtDocumentStart
duo.我还没有找到在
window.onload
之前使用WKUserScript
/ WKUserScriptInjectionTimeAtDocumentStart
duo 注入自定义 js 的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.