I am trying to replicate a service that is provided by Tynt.com that appends some text to a user's selection when copying. I understand that users don't particularly like this, but it is a client's request to append the URL and copyright notice whenever a user copies something from their website.
In current browsers, I am able to do this by creating a DOM element, adding the selected text, appending the copyright text and then selecting the new node:
var newSelection = document.createElement( 'div' );
newSelection.style.cssText = "height: 1px; width: 1px; overflow: hidden;";
if( window.getSelection )
{
var selection = window.getSelection( );
if( selection.getRangeAt )
{
var range = selection.getRangeAt( 0 );
newSelection.appendChild( range.cloneContents( ) );
appendCopyright( );
document.body.appendChild( newSelection );
selection.selectAllChildren( newSelection );
// ... remove element, return selection
}
}
In IE9, this errors out on the selection.selectAllChildren( newSelection ) statement and I was able to figure out that this is because newSelection was effectively "hidden" from the viewport due to the styles applied in the second line above.
Commenting that out works, but obviously the new node is shown to the end user. It appears that this was resolved in later versions of IE, but I am having trouble coming up with a workaround that is sufficient for IE9, a browser that I need to support.
I've tried a variety of alternatives, like setting visibility: hidden;, positioning it off-screen, and trying some alternative selection functions, but they each present different problems.
The error thrown by IE is: SCRIPT16389: Unspecified error.