Getting source HTML from a WebView in Cocoa

徘徊边缘 提交于 2019-12-18 13:25:37

问题


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!


回答1:


You can ask for the WebView's -selectedDOMRange and you'll get a DOMRange object 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, see DOMRange.h for what methods/properties it supports.

You can then replace the current selection using the -replaceSelectionWithMarkupString:, -replaceSelectionWithText: or -replaceSelectionWithNode: methods of WebView.




回答2:


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];



回答3:


UIWebView lets you run arbitrary JavaScript:

[webview stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"]


来源:https://stackoverflow.com/questions/2046381/getting-source-html-from-a-webview-in-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!