看到那个帖子
http://blog.techno-barje.fr/post/2010/10/06/UIWebView-secrets-part3-How-to-properly-call-ObjectiveC-from-Javascript/
以及如何从 Javascript 调用 Objective-C?
您可以使用脚本向您的 UIWebView 发送一些字符串
function sendURLToUIWebView(url) {
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
}
你的网址应该有特定的方案myappcomand://
你可以用UIWebViewDelegate
方法处理它(设置一些对象作为 UIWebView 的委托,一些 UIViewController)
- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
BOOL shouldLoad = YES;
if ([request.URL.scheme isEqualToString:@"myappcomand"]) {
shouldLoad = NO;
// parse url string "request.URL" and extract your parameters to store them
}
return shouldLoad;
}
你的 javascript 函数
function sendURLToUIWebView(url) {
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
}
function getRangeForSelectedText() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var url = "myappcomand://" + "range=" + range; // you should convert range to string
sendURLToUIWebView(url);
}
更新:
范围到字符串
range.toString().replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '')
要不就var rangeText = window.getSelection().toString();
请参阅range.toString() 的奇怪行为