使用Javascript删除UIWebView中的链接?

时间:2011-10-17 20:23:47

标签: javascript iphone objective-c xcode uiwebview

我有一个以编程方式创建的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......./"]]];

}

我还有以下委托方法;

我正在尝试删除UIWebView中的所有链接,因此我的用户无法离开我编码的URL。我尝试了以下方法来更改链接的颜色;

- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webNews stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\"a.link\", \"color:#FFFFFF\")"];
}

我已经阅读了使用javascript从UIWebView中删除所有链接的人的示例,但我似乎无法使其正常工作。任何人都可以在我需要做的方法中提供一个例子吗?

2 个答案:

答案 0 :(得分:1)

你在这里做的是使所有与“链接”类的链接看起来像普通文本,而不是让它们不可点击。您可以使用以下代码使链接无效:

Array.prototype.forEach.call(document.querySelectorAll('a:link'), function(link) {link.href="javascript://"});

当然,它们看起来仍然可以点击。你可以用更像这样的东西删除它们:

Array.prototype.forEach.call(document.querySelectorAll('a:link'), function(link) {
    while(link.firstChild && link.parentElement) {
        link.parentElement.insertBefore(link.firstChild, link);
        link.parentElement.removeChild(link);
    }
});

但这会产生各种其他副作用。这实际上取决于你想要实现的目标。

更新parentNode切换到parentElement并添加了检查以跳过无父链接。

答案 1 :(得分:1)

您确定用户从您正在加载的页面导航的唯一方法是触摸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