简体   繁体   English

如何将 Objective-C 值传递给 JavaScript

[英]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:假设:

  • it's a URL request you initiate from the app that will land you on the page(opposed to navigating to some link later on)这是您从应用程序发起的 URL 请求,该请求将使您进入页面(反对稍后导航到某个链接)
  • you don't want to pass sensitive data你不想传递敏感数据

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.

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