问题
I am creating a mac application and it requires to have a functionality the same as that is available in the Apple mail for adding and editing the urls in the mail.
If I do the below, I get the problem that it does not detects the selected text as link
DOMRange *selectedDomRange = [self.cannedResponseWebView selectedDOMRange];
DOMNode *commonNode = [selectedDomRange commonAncestorContainer];
DOMNode *parentNode = [commonNode parentNode];
NSString *linkDisplay = [[[parentNode attributes] getNamedItem:@"href"] nodeValue];
Could someone help me out with this. Please let me know if anyone is not able to understand the issue.
回答1:
Finally I was able to solve the problem. Please find the below code snippet:
- (NSString *)webViewContainURLString:(WebView *)webView {
DOMNode *selectedNode = [[[webView selectedDOMRange] commonAncestorContainer] parentNode];
DOMNode *anchorNode = [self nodeContaingAnchorNode:selectedNode];
NSString *urlString = [[[anchorNode attributes] getNamedItem:@"href"] nodeValue];
return urlString;
}
- (DOMNode *)containingAnchorNode:(DOMNode *)selectedNode {
DOMNode *startingNode = selectedNode;
DOMNode *finalNode = nil;
if (selectedNode) {
while (startingNode) {
if ([[startingNode attributes] getNamedItem:@"href"]) {
finalNode = startingNode;
break;
}
startingNode = [startingNode parentNode];
}
}
return finalNode;
}
来源:https://stackoverflow.com/questions/39807402/webview-adding-and-editing-text-as-a-link-objective-c