1. 程式人生 > >iOS webview 和 js 互動

iOS webview 和 js 互動

1.先上一段 html 程式碼

<html>

<head>

<meta http-equiv="Content-Type"content="text/html; charset=utf8">

</head>

<body>

        <h1>這是一段內容</h1>

<input type="button"value="測試"onclick="check()" />

<input type="button"value="測試2"onclick="check2()"/>

</body>

</html>


2. js 程式碼

function loadURL(url) {

    var iFrame;

    iFrame = document.createElement("iframe");

    iFrame.setAttribute("src", url);

    iFrame.setAttribute("style", "display:none;");

    iFrame.setAttribute("height", "0px");

    iFrame.setAttribute("width", "0px");

    iFrame.setAttribute("frameborder"

, "0");

    document.body.appendChild(iFrame);

// 發起請求後這個iFrame就沒用了,所以把它從dom上移除掉

    iFrame.parentNode.removeChild(iFrame);

    iFrame = null;

}

function check() {

    loadURL("lichongyang:abc");

}

function check2() {

    loadURL("lichongyang2:abc");

}


3.當js 呼叫 iOS 的時候 通過上面的js 程式碼 會重定向一個 請求的url  在

- (BOOL

)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    NSURL * url = [request URL];

if ([[url absoluteString] rangeOfString:@"abc"].location!= NSNotFound) {

UIAlertView * alertView = [[[UIAlertViewalloc] initWithTitle:@"test"message:[url absoluteString] delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil] autorelease];

        [alertView show];

        return NO;

    }

//獲取當前頁面的title

//self.title   [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

return YES;

}