質問

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.

役に立ちましたか?

解決

Interesting. I haven't come across that before. Have you tried using IE < 11's other selection/TextRange API instead? No idea if it'll work but it's worth a try:

document.body.appendChild( newSelection );

if (document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(newSelection);
    textRange.select();
} else {
    selection.selectAllChildren( newSelection );
}

他のヒント

I just realized that I had not tried setting the CSS opacity: 0. Strangely, IE9 doesn't consider transparent nodes to be hidden from the viewport.

var newSelection = document.createElement( 'div' );
newSelection.style.cssText = "opacity: 0;";

However, if I also position the element, in order to avoid affecting the layout, it yields the same error.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top