Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting source HTML from a WebView in Cocoa

I'm working on a OS X program where the user does some light WYSIWYG HTML editing in a WebView. Being new to programming with Cocoa and WebKit, I have absolutely no idea how to get selected text from a WebView - the intention being to take what the user selected, add HTML code (like div's or span's) around the text, and replace the selected text with the modified code. How can this be accomplished?

I'm currently programming this project with MacRuby, but I'd appreciate help from Objective-C programmers as well. Thank you!

like image 954
Jim C Avatar asked Jan 12 '10 02:01

Jim C


2 Answers

Apple recommends using this snippet here to retrieve the HTML content of a WebKit WebView:

[(DOMHTMLElement *)[[[webView mainFrame] DOMDocument] documentElement] outerHTML];

If you want the HTML interpreted as plain text, you can use:

[(DOMHTMLElement *)[[[webView mainFrame] DOMDocument] documentElement] outerText];
like image 116
CodaFi Avatar answered Oct 05 '22 02:10

CodaFi


UIWebView lets you run arbitrary JavaScript:

[webview stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"]
like image 39
Marcelo Cantos Avatar answered Oct 05 '22 00:10

Marcelo Cantos