我有一个以编程方式创建的 UIWebView,如下所示;
- (void)loadView {
UIView *webNewsView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = webNewsView;
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
webFrame.origin.y = 0.0f;
webNews = [[UIWebView alloc] initWithFrame:webFrame];
webNews.backgroundColor = [UIColor clearColor];
webNews.scalesPageToFit = YES;
webNews.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
webNews.delegate = self;
webNews.dataDetectorTypes = UIDataDetectorTypeNone;
[self.view addSubview: webNews];
[webNews loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://..........MYURL......./"]]];
}
我还有以下委托(delegate)方法;
我正在尝试删除 UIWebView 中的所有链接,以便我的用户无法导航离开我编码的 URL。我已尝试以下方法来更改链接的颜色;
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webNews stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\"a.link\", \"color:#FFFFFF\")"];
}
我已经阅读了人们使用 javascript 删除 UIWebView 中所有链接的示例,但我似乎无法正常工作。任何人都可以在我需要做的方法中提供一个示例吗?
最佳答案
您确定用户从您正在加载的页面导航的唯一方法是触摸 A
元素吗?设置 window.location
的表单提交按钮或 JavaScript 事件处理程序怎么样?
据我所知,防止导航的万无一失的方法是实现webView:shouldStartLoadWithRequest:navigationType
以返回NO
,除了第一个请求:
@interface MyDelegate <UIWebViewDelegate>
{
BOOL didStartFirstRequest;
}
@end
@implementation MyDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (didStartFirstRequest)
return NO;
didStartFirstRequest = YES;
return YES;
}
@end
更新
UIWebView
已被弃用一段时间,现在改用 WKWebView
。如果您使用的是 WKWebView
,您需要设置其 navigationDelegate
,并在委托(delegate)中实现 webView(_:decidePolicyFor:preferences:decisionHandler:)
方法。
关于javascript - 使用 Javascript 删除 UIWebView 中的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7799127/