【问题标题】:javascript event Handler in uiwebviewuiwebview 中的 javascript 事件处理程序
【发布时间】:2011-07-29 05:55:43
【问题描述】:

我正在我的 iPhone 应用程序中显示一个 UIWebView。在 UIWebView 我显示的 HTML 页面也有 JavaScript。我想在 HTML 页面中单击一个按钮时调用方法(X Code)。

我该怎么做。 谢谢

【问题讨论】:

    标签: iphone objective-c xcode


    【解决方案1】:

    如果我正确理解了您的问题,您想从 UIWebView 中的 javascript onClick 事件处理程序调用 Objective C 方法。这样做的方法是将浏览器重定向到在您的 javascript 代码中使用自定义方案的 URL,如下所示:

    function buttonClicked() {
        window.location.href = "yourapp://buttonClicked";
    }
    

    回到 Objective C,声明你的视图控制器符合UIWebViewDelegate 协议,

    @interface DTWebViewController : DTViewController <UIWebViewDelegate> {
    ...
    

    将您的控制器设置为 Web 视图的委托,

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.webView.delegate = self;
    }
    

    并在 URL 加载之前拦截它:

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        if ([[request.URL scheme] isEqual:@"yourapp"]) {
            if ([[request.URL host] isEqual:@"buttonClicked"]) {
                [self callYourMethodHere];
            }
            return NO; // Tells the webView not to load the URL
        }
        else {
            return YES; // Tells the webView to go ahead and load the URL
        }
    }
    

    【讨论】:

    • 酷,这也适用于拦截锚点击,navigationType 将是 UIWebViewNavigationTypeLinkClicked
    • 函数 buttonClicked() { window.location.href = "yourapp://buttonClicked"; } 你能告诉更多关于这些行的信息
    • 这适用于以下更改:yourapp://buttonClicked 应该包含一个主机组件,例如 yourapp://www.yourapp.com/buttonClicked。然后路径将是“/buttonClicked”。否则,它将是一个空字符串。
    • 这在 ios9 上对我不起作用,有人知道为什么吗?
    • 嗨,我正在将您的代码与 Swift 一起使用,但没有任何反应,我的代码:unc webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest,navigationType: UIWebViewNavigationType)-> Bool{ if (request .URL!.scheme == "index//clickFunction") { self.move() return false } else return true。以为,request等于“index//clickFunction”,它运行到else返回true。那么,请问我哪里错了?
    【解决方案2】:

    Swift 版本

    webView.delegate = self
    
    extension ViewController: UIWebViewDelegate {
        func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            if request.description == "yourappname://buttonClicked" {
    
                // do your stuff here
                return false
            }
            return true
        }    
    }
    

    示例 HTML

    <a href="yourappname://buttonClicked">
        <img src="http://someurl.com/table_desktop.jpg"/ width="100%">
    </a>
    

    如果您想知道如何在wkWebView 中进行操作,这里是link

    【讨论】:

    • 它在迅速。不客观 c
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    相关资源
    最近更新 更多