【问题标题】:IOS to call javascript notify functionIOS调用javascript通知函数
【发布时间】:2016-03-09 05:07:04
【问题描述】:

我的应用就像 iBook。正在将 html 文件加载到 webview 中。

我有一个 html 文件加载到 webview..

 <img class="play_icon" src="images/play_icon.png" onclick="javascript:window.external.notify('Home pregnancy test.mp4')" />

如何从objective c调用javascript函数window.external.notify()

如何获取此通知并获取目标 c 中的视频网址

【问题讨论】:

    标签: javascript ios objective-c


    【解决方案1】:

    请看下面的解决方案

    <!DOCTYPE html>
    <html>
        <head>
            <script>
                function yourFunctionName()
                {
                    alert("Hello World!");
                }
                </script>
        </head>
    
        <body>
            <button onclick="yourFunctionName()">Try it</button>
        </body>
    </html>
    

    你的 Obj-C 代码

    NSString *path;
    NSBundle *thisBundle = [NSBundle mainBundle];
    path = [thisBundle pathForResource:@"first" ofType:@"html"];
    NSURL *instructionsURL = [NSURL fileURLWithPath:path];
    [webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
    
     NSString * jsCallBack = [NSString stringWithFormat:@"yourFunctionName()"];
     [webView stringByEvaluatingJavaScriptFromString:jsCallBack];
    
    [webView stringByEvaluatingJavaScriptFromString:@"yourFunctionName()"];
    

    您需要通过以下方式实现执行,因为在一个地方实现上述 Obj-C 将不起作用。因此,您必须按照以下方式进行操作。原因是工作将以异步方式进行,这就是为什么

    在UIWebViewDelegate中调用如下函数

    [webView stringByEvaluatingJavaScriptFromString:@"yourFunctionName()"];
    

    回调方法应该在--webViewDidFinishLoad:

    如果您需要更多信息,请查看以下链接

    Using JavaScript From Objective-C

    希望对你有帮助

    【讨论】:

    • 您好,谢谢您的回复。但是在我的 html 中没有脚本文件。我试过这种方式。不工作。通知功能就像警报一样,无需使用 webview 将通知的脚本。但我不知道如何调用
    • 您可以在同一个html文件中编写一个javascript函数。只需编写一个示例函数并测试调用是否通过。一旦调用通过,您将能够实现您的要求。
    • 您好,我尝试了警报功能。它工作正常。弹出警报。但我不知道如何调用此通知。他们在 html 中提到 onclick="javascript:window.external.notify('Home妊娠 test.mp4')"
    • 当我提到 onclick = "javascript:alert()" 它工作正常。但是我如何调用上述方法并从 html 文件中获取 .mp3 文件名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多