在webview中加载本地javascript?

时间:2015-09-15 09:15:28

标签: javascript ios iphone swift webview

我在swift中使用我自己的广告制作移动浏览器,我想运行脚本。我已经注入了javascript本地文件,但它在其他窗口中打开并覆盖webview内容。是否可以在webview中运行javascript代码页?不在其他窗口,只在包含页面内容的页面中。希望你能得到它

1 个答案:

答案 0 :(得分:5)

使用WKWebView进行javascript方法调用:

第1步。导入webkit的类

Obj-C:#import <WebKit/WebKit.h>
斯威夫特:import WebKit

第2步。创建WKWebView实例(不幸的是,它只能以编程方式完成)

Obj-C @property (strong, nonatomic) WKWebView *wkWebView;

Swift var wkWebView: WKWebView? = WKWebView()

第3步。然后在viewDidLoad

的OBJ-C:

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

    NSString *scriptSourceCode = @"your javascript code here";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];

    WKUserContentController *controller = [[WKUserContentController alloc] init];
    [controller addUserScript:script];

    configuration.userContentController = controller;

    _wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

    [self.view addSubview:_wkWebView];

夫特:

    let configuration = WKWebViewConfiguration()
    let controller = WKUserContentController()

    let scriptSourceCode = "your javascript code here"
    let script = WKUserScript(source: scriptSourceCode, injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true)
    controller.addUserScript(script)

    configuration.userContentController = controller

    self.wkWebView = WKWebView(frame: self.view.frame, configuration: configuration)

    self.view.addSubview(self.wkWebView!)

第4步wkWebView中加载HTML字符串(或loadRequest):

的OBJ-C:

[_wkWebView loadHTMLString:_desiredHTML baseURL:[[NSBundle mainBundle] bundleURL]];

夫特:

self.wkWebView?.loadHTMLString(_desiredHTML, baseURL: NSBundle.mainBundle().bundleURL)

第5步。调用WKWebView

中包含的javascript中存在的方法

的OBJ-C:

    NSString *callMethod = [NSString stringWithFormat:@"existingMethodWithParam(%@)", stringParam];

    [_wkWebView evaluateJavaScript:callMethod
             completionHandler:^(id obj, NSError *error) {

                 if (error)
                 {
                     NSLog(@"ERROR evaluating JavaScript - %@", error);
                 }
                 else 
                 {
                     NSLog(@"Returned value - %@", obj); //if the javascript method has a return type
                 }
             }];

夫特:

    let callMethod = String(format: "existingMethodWithParam(%@)", stringParam)

    [self.wkWebView?.evaluateJavaScript(callMethod, completionHandler: { (obj, error) -> Void in

        println(obj)
        println(error)
    })]