OGeek|极客世界-中国程序员成长平台

标题: ios - 在 WKWebView 中注入(inject)全局对象 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:34
标题: ios - 在 WKWebView 中注入(inject)全局对象

我正在尝试向 WKWebView 添加一个全局对象,其中加载的 HTML 期望存在某个对象(使用 API)。我有以下设置在加载后启动 HTML。这在以下简单示例中有效,但使用 loadRequest 加载的“真实”内容会失败,并显示“[Error] ReferenceError: Can't find variable”。有人有类似经历吗?

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupWebView];
}

- (void)setupWebView
{
    WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];

    NSString* jsCode =
    @"var TheObject = function() {}; \
    TheObject.prototype.sendTheMessage = function() { \
      window.webkit.messageHandlers.performAction.postMessage(messageToPost); \
    }; \
    var theObject = new TheObject();";

    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsCode
                                                      injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                   forMainFrameOnly:NO];
    [userContentController addUserScript:userScript];
    [userContentController addScriptMessageHandler:self
                                              name"performAction"];
    webConfiguration.userContentController = userContentController;

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
                                      configuration:webConfiguration];
    [self.view addSubview:self.webView];

    [self.webView loadHTMLString:
     @"<body onload='sendMessage()'> \
     <script>function sendMessage() { \
       theObject.sendTheMessage(); \
     } \
     </script> \
     Attempting to send the message \
     </body>" baseURL:nil];
}

- (void)userContentControllerWKUserContentController *)userContentController didReceiveScriptMessageWKScriptMessage *)message
{
    NSLog(@"%@", message);
}

@end



Best Answer-推荐答案


示例和我的生产代码的唯一区别是我加载了要从文件中注入(inject)的 javascript。在这个文件中有一个错字。表明尝试将问题简化为示例代码有助于识别您的愚蠢错误!

关于ios - 在 WKWebView 中注入(inject)全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33282040/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4