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!
You can ask for the
WebView‘s-selectedDOMRangeand you’ll get aDOMRangeobject back. You can use this object to find out what is selected.DOMRange, like all WebKit DOM objects, is an Objective-C representation of a standard W3C DOMRange object, seeDOMRange.hfor what methods/properties it supports.You can then replace the current selection using the
-replaceSelectionWithMarkupString:,-replaceSelectionWithText:or-replaceSelectionWithNode:methods ofWebView.