【问题标题】:WKWebView Evaluate Javascript without reloading pageWKWebView 在不重新加载页面的情况下评估 Javascript
【发布时间】:2014-07-22 00:19:31
【问题描述】:

目前我只能通过将其添加到 webview 的配置的 userContentController 并重新加载页面来弄清楚如何评估 javascript:

WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[self.webView.configuration.userContentController addUserScript:script];
[self.webView reload];

如何在我的 WKWebView 上执行类似于旧 WebView 的 stringByEvaluatingJavaScriptFromString: 的 javascript,这样我就不必重新加载页面?

我正在尝试获得与

相同效果的东西
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ", width]];

【问题讨论】:

    标签: objective-c cocoa wkwebview


    【解决方案1】:
    [webView evaluateJavaScript:javascriptString completionHandler:nil];
    

    执行与您为 UIWebView 列出的功能相同的功能

    【讨论】:

      【解决方案2】:

      你只能在初始化时通过初始化设置WKWebViewConfiguration

      [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
      

      对属性configuration 的所有调用都会在运行时的后期复制(请参阅文档和头文件)。所以基本上你对前三行代码所做的是将WKUserScript 设置为从未使用过的WKWebViewConfiguration - 因此无法正常工作。

      正确的做法:

      NSString *scriptString = @"Some javascript";
      WKUserScript *script = [[WKUserScript alloc] initWithSource:scriptString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
      WKUserContentController *userContentController = [[WKUserContentController alloc] init];
      [userContentController addUserScript:script];
      WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
      configuration.userContentController = userContentController;
      _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
      

      完成此操作后,您将不再需要 evaluateJavaScript:

      P.S.:我在我的小项目STKWebKitViewController on GitHub 中使用此代码。也许这也可以节省您的时间!

      【讨论】:

      • 如果需要连续调用网页怎么办?你会每次都调用 addUserScript 吗?
      • 请定义“连续”。这种方法在每次页面加载时运行相同的 JavaScript。如果您想更改正在执行的脚本,evaluateJavaScript: 可能是您更好的解决方案。
      • 假设您需要调用该函数并将当前时间戳作为参数传递给每个 uibutton 点击​​。您会怎么做?
      • 绝对是evaluateJavaScript:!正如您在上面的代码中看到的那样,使用 WKUserScripts 只能在文档开始或结束时执行,而不是针对按钮单击等自定义事件。
      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多