简体   繁体   English

如何将 UIWebView 中的 JSContext 重新用于 WKWebview 的 WKScriptMessage

[英]How do I repurpose JSContext in UIWebView to WKScriptMessage for WKWebview

I want to convert a UIWebView library to use WkWebview.我想将 UIWebView 库转换为使用 WkWebview。 The remaining piece is switching out JSContext because the valueForKeyPath doesn't work anymore.剩下的部分是切换 JSContext 因为valueForKeyPath不再起作用了。 So how do I rewrite something like the following to use WKScriptMessage as the other SO link suggests?那么我该如何重写类似下面的内容以使用 WKScriptMessage 作为其他 SO 链接所建议的? (swift or ObjC answer is fine) How to get JSContext from WKWebView (swift 或 ObjC 答案很好) 如何从 WKWebView 获取 JSContext

JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];


ctx[@"contentPasteCallback"] = ^(JSValue *msg) {
    __weak typeof(weakSelf) StrongSelf = weakSelf;
    StrongSelf.editorPaste = YES;
};

[ctx evaluateScript:@"document.getElementById('zss_editor_content').addEventListener('paste', contentPasteCallback, false);"];

I have converted UIWebView to WKWebView for Editor.我已将WKWebView转换为UIWebView以供编辑器使用。 I have created fork from this Github Link .我已经从这个Github Link创建了叉子。 The link to my demo can be found here .我的演示链接可以在这里找到。

Ok I figured it out.好的,我想通了。 See the PR https://github.com/nnhubbard/ZSSRichTextEditor/pull/243请参阅 PR https://github.com/nnhubbard/ZSSRichTextEditor/pull/243

Basically you inject javascript to start the listeners.基本上你注入 javascript 来启动监听器。 The key here is to pass the function which calls webkit using postMessage and use the same name, in my case 'jsm' as what was setup when you create the WKUserContentController object这里的关键是传递 function ,它使用postMessage调用 webkit 并使用相同的名称,在我的例子中是'jsm' ,就像你创建WKUserContentController object 时设置的那样

    NSString *pasteListener = @"document.getElementById('zss_editor_content').addEventListener('paste', function() {window.webkit.messageHandlers.jsm.postMessage('paste');});";

    [self.editorView evaluateJavaScript:pasteListener completionHandler:^(NSString *result, NSError *error) {
        if (error != NULL) {
            NSLog(@"%@", error);
        }
    }];

and then you listen for the response in the userContentController: didReceiveScript delegate method from WKScriptMessageHandler然后你在userContentController: didReceiveScript来自WKScriptMessageHandler的 didReceiveScript 委托方法

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

    NSString *messageString = (NSString *)message.body;
    if ([messageString isEqualToString:@"paste"]) {
        self.editorPaste = YES;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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