我正在开发一个也具有相关网站(本质上是镜像功能)的应用程序,并且我正在寻找在现有应用程序中引入UIWebView中显示的一些HTML元素的方法,这些元素可能包含链接。
这些页面也可以在应用程序的 Web 版本上查看,并且将是指向现有页面的链接,我需要能够拦截触摸事件并将用户路由到应用程序内的相关本机视图控制器,而不是触发页面加载。
我知道如何通过UIWebView的代表来做到这一点,但我想知道是否有一些技巧甚至框架有人知道来实现它。
UIWebView将html页面加载到您的应用程序中,您可以链接到存在页面。如果你想让html代码与原生代码通信,可以通过js调用使用三种方式。
一个是XMLHttpRequest:
var xmlhttp;
function sendRequest()
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
//url should be http://
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET","http://www.baidu.com",true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
alert("status code is 200")
}
else
{
alert("Problem retrieving XML data");
}
}
}
另一个是Iframe:
function sendIframeRequest () {
var iframe = document.createElement("iframe");
var url= "myapp:" + "&func=iFrameCall" ;
url = "http://www.baidu.com";
iframe.src = url;
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.parentNode.removeChild(iFrame);
iframe = null;
}
或使用 document.location
function sendDocumentRequest ()
{
var url= "cpcall:" + "&class=CPCameraPlugin¶meters=camera";
document.location = url;
}
在本机端,有两种方式可以处理 js 请求,一种使用 UIWebView 委托:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest * )request navigationType:(UIWebViewNavigationType)navigationType
另一个你可以注册一个NSURLProtocol,使用以下函数来处理它:
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
//do what you want
}
著名的框架是cordova,它是一个使用HTML,CSS和JavaScript构建本机移动应用程序的平台。你可以用它检查,项目位置是 在此处输入链接说明