Cocoa NSWebView, editable and paste

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

I recently had a problem with an editable webview in my application. The paste or cmd-v was correctly working for a text/plain or text/html clipboardData, but copying an URL from the browser top bar, and pasting it in the webview was not working at all (nothing at all is appearing).

Here is how I did:

1. set your webView editable: 

[myWebView setEditable:YES];

2. load your html in the webView:

[[myWebView mainFrame] loadHTMLString:yourhtml baseURL:nil];

(yourhtml is your html code …)

3. set the onpaste handler:

when the html is really loaded, use this delegate:

-(void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame

{

    NSString *scriptJava = @"function pasteHtmlAtCaret(html) {var sel, range;if (window.getSelection) {sel = window.getSelection();if (sel.getRangeAt && sel.rangeCount) {range = sel.getRangeAt(0);range.deleteContents();var el = document.createElement(\"div\");el.innerHTML = html;var frag = document.createDocumentFragment(), node, lastNode;while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node);}range.insertNode(frag);if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode);  range.collapse(true);    sel.removeAllRanges();    sel.addRange(range);}}} else if (document.selection && document.selection.type != \"Control\") {document.selection.createRange().pasteHTML(html);}} function mymiaforgmailpastefunc(e){if (e.clipboardData.getData('text/uri-list')){e.stopPropagation(); e.preventDefault();  var ins = e.clipboardData.getData('text/plain');pasteHtmlAtCaret('<a href=\"'+ins+'\">'+ins+'</a>');}}";

    

    [body stringByEvaluatingJavaScriptFromString:scriptJava];

    DOMNodeList *htmlNodeList = [[[body mainFrame] DOMDocument] getElementsByTagName:@"body"];

    DOMHTMLElement *htmlNode = (DOMHTMLElement *) [htmlNodeList item:0];

    [htmlNode setAttribute:@"onpaste" value:@"mymiaforgmailpastefunc(event)"];

}

The javascript above is a set of 2 functions. The first one is used to insert html at the current caret position. The second is my paste handler. It detects if the clipboard contains an url with the text/uri-list key, then takes the text/plain value and creates the html code with the ahref. If there is no text/uri-list, we don’t call event preventdefault, and let the webkit manage the paste…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>