Home > Web Front-end > H5 Tutorial > Interaction instructions between IOS, HTML5, and Javascript

Interaction instructions between IOS, HTML5, and Javascript

伊谢尔伦
Release: 2017-01-23 16:41:59
Original
2013 people have browsed it

When using the html js css file in the project in an iOS project, sometimes there will be an error in the reference path, causing the html js css image file to fail to load.

Then, the correct operation method for introducing H5 related files is as follows, so that there will be no situation where resource files cannot be imported and used normally.

1. iOS uses the webView control to load local html5 or html5 on the network

Note: In the article, I mainly explain the webView control to load local html5. As for loading network html5, this is the same! Just need to get the html5 code from the network interface!

Preparation work

1>. First, you can drag and drop the written html file into the iOS project directory;

As shown below:

Interaction instructions between IOS, HTML5, and Javascript

2>. In the Xcode project, drag a UIWebView control into the storyboard for easy use later;

As shown below:

Interaction instructions between IOS, HTML5, and Javascript

3>.Set the controller as the proxy of webView and comply with the protocol; use the webView control to load local html5;

As shown in the figure below:

Interaction instructions between IOS, HTML5, and Javascript

4>. Finally, we use the iOS simulator to see the effect of the project after running (here, in order to let everyone see the simulator effect more clearly, I changed the background color of the page to yellow. We will talk about how to modify the background color of the UIWebView page later);

Interaction instructions between IOS, HTML5, and Javascript

Of course, for students with iOS foundation, the above operations of loading local html5 or loading network html5 are all It's very simple. Many students are confused about how to modify the content in HTML5 when the webView interface displayed in the network interface does not meet our needs, which is what we usually call add, delete, modify, and check! Next, I will explain to you how to obtain tags in html5 and how to modify the content in html5!

Modify html5 content in iOS

Implement the proxy method webViewDidFinishLoad: to operate the web page, and operate the tags in html5 (add, delete, modify and check) in the proxy method;

Code The operations in are as follows:

Interaction instructions between IOS, HTML5, and Javascript

Rerun the project and let’s take a look at the effect changes in the simulator:

Interaction instructions between IOS, HTML5, and Javascript

Description : (To understand the code in the string, you must have basic knowledge of JS) As can be seen from the simulator, we successfully deleted the P tag with the id of 'paragraph' and changed the tag with the class of 'BaiDu'. The content (modified from 'Baidu' to 'Let education return to its essence'), and a picture was successfully uploaded later!

Several steps to operate html5 in iOS:

1. Use the webView control to load local html5 or html5 on the network;

2.Set the current controller object to webView The proxy object of the agent and abide by the protocol;

3. Use the class selector or id selector or label selector to select the label to be operated;

4. Get the The tag is converted into a string;

5. webView calls the stringByEvaluatingJavaScriptFromString method to execute the js code;

Pay attention to the application scenario of modifying the html5 content here: for example, loading a link on the network, but If you don’t want a certain link tag, use this proxy method to get the tag, then delete it, or change the display text of his tag, etc.;

Interaction between iOS, Html5 and JS

The first framework used is WebViewJavascriptBridge. Using this framework can facilitate the interaction between iOS and JS

1, flow chart

Interaction instructions between IOS, HTML5, and Javascript

2. Use on IOS side

//首先导入#import "WebViewJavascriptBridge.h"文件
//第一步:开启日志
 
// 开启日志,方便调试
[WebViewJavascriptBridge enableLogging];
 
//第二步:给ObjC与JS建立桥梁
 
// 给哪个webview建立JS与OjbC的沟通桥梁
self.bridge = [WebViewJavascriptBridgebridgeForWebView:webView];
 
// 设置代理,如果不需要实现,可以不设置
[self.bridgesetWebViewDelegate:self];
 
//第三步:注册HandleName,用于给JS端调用iOS端
 
// JS主动调用OjbC的方法
// 这是JS会调用getUserIdFromObjC方法,这是OC注册给JS调用的
// JS需要回调,当然JS也可以传参数过来。data就是JS所传的参数,不一定需要传
// OC端通过responseCallback回调JS端,JS就可以得到所需要的数据
[self.bridgeregisterHandler:@"getUserIdFromObjC"handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getUserIdFromObjC, data from js is %@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"userId": @"123456"});
    }
}];
  
[self.bridgeregisterHandler:@"getBlogNameFromObjC"handler:^(id data, WVJBResponseCallback responseCallback) {
    NSLog(@"js call getBlogNameFromObjC, data from js is %@", data);
    if (responseCallback) {
      // 反馈给JS
      responseCallback(@{@"blogName": @"星仔"});
    }
}];
 
//第四步:直接调用JS端注册的HandleName
 
[self.bridgecallHandler:@"getUserInfos"data:@{@"name": @"ddsds"}responseCallback:^(id responseData) {
    NSLog(@"from js: %@", responseData);
}];
Copy after login

3. Use on Javascript side

<script>
      window.onerror = function(err) {
        log(&#39;window.onerror: &#39; + err)
      }
    
      /*这段代码是固定的,必须要放到js中*/
      function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement(&#39;iframe&#39;);
        WVJBIframe.style.display = &#39;none&#39;;
        WVJBIframe.src = &#39;wvjbscheme://__BRIDGE_LOADED__&#39;;
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
      }
    
      /*与OC交互的所有JS方法都要放在此处注册,才能调用通过JS调用OC或者让OC调用这里的JS*/
      setupWebViewJavascriptBridge(function(bridge) {
       var uniqueId = 1
       function log(message, data) {
         var log = document.getElementById(&#39;log&#39;)
         var el = document.createElement(&#39;div&#39;)
         el.className = &#39;logLine&#39;
         el.innerHTML = uniqueId++ + &#39;. &#39; + message + &#39;:<br/>&#39; + JSON.stringify(data)
         if (log.children.length) {
            log.insertBefore(el, log.children[0])
         } else {
           log.appendChild(el)
         }
       }
       /* Initialize your app here */
       
       /*我们在这注册一个js调用OC的方法,不带参数,且不用ObjC端反馈结果给JS:打开本demo对应的博文*/
     bridge.registerHandler(&#39;openWebviewBridgeArticle&#39;, function() {
         log("openWebviewBridgeArticle was called with by ObjC")
     })
      /*JS给ObjC提供公开的API,在ObjC端可以手动调用JS的这个API。接收ObjC传过来的参数,且可以回调ObjC*/-
      bridge.registerHandler(&#39;token&#39;, function(data, responseCallback) {
         log("G星爷: ", data)
       responseCallback({这里给我返回拼接后的地址})
     })
      /*JS给ObjC提供公开的API,ObjC端通过注册,就可以在JS端调用此API时,得到回调。ObjC端可以在处理完成后,反馈给JS,这样写就是在载入页面完成时就先调用*/
       bridge.callHandler(&#39;getUserIdFromObjC&#39;, function(responseData) {
        log("JS call ObjC&#39;s getUserIdFromObjC function, and js received response:", responseData)
      })
       document.getElementById(&#39;blogIds&#39;).onclick = function (e) {
         log(&#39;js call objc: getBlogNameFromObjC&#39;)
         bridge.callHandler(&#39;ww&#39;, {&#39;blogdURL&#39;: &#39;weidsfdl&#39;}, function(response) {
                          log(&#39;JS got response&#39;, response)
                          })
       }
     })
       
    </script>
Copy after login

4. Note

  1. 当出现这样的提示的话,说明JS那边已经实现了名字为‘ww’的方法,但是iOS这边没有注册,

Interaction instructions between IOS, HTML5, and Javascript

具体实现是:
[self.bridgeregisterHandler:@"ww"handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"js call getBlogNameFromObjC, data from js is %@", data); if (responseCallback) { // 反馈给JS responseCallback(@{@"blogName": @"星仔"}); } }];

2. 当在push或者说页面消失的时候,将bridge对象置为空。

五,防止WebView长按实现的方法

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    // 禁用 页面元素选择
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect=&#39;none&#39;;"];
    
//     禁用 长按弹出ActionSheet
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout=&#39;none&#39;;"];
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template