Rob
Rob

Reputation: 1777

Javascript document paste event - get pasted text in FireFox

It's been asked many times on here, and from my research, Firefox has a paste event but you cannot directly read the contents of the pasted text as illustrated here:

http://support.mozilla.com/en-US/kb/Granting%20JavaScript%20access%20to%20the%20clipboard

and here:

http://codebits.glennjones.net/editing/getclipboarddata.htm

In IE and Chrome you can examine the clipboardData field, in FireFox you can't.

There are many solutions to this about, but none of them great.

So here's the question:

You can read the contents of the document/element before and after paste, so you can have the two strings. Question is, has anyone written a simple diff function which would determine what was pasted into the document?

Or alternatively, anyone know of a better way in firefox to figure out what was pasted?

My ultimate goal is to be able to figure out what was pasted and strip tags and other debris from the pasted text, then re-paste a cleaned version manually.

Any help would be appreciated.

Upvotes: 2

Views: 3224

Answers (2)

Jaykul
Jaykul

Reputation: 15814

This is now fixed, and from Firefox 22 on, this will work in the paste event:

event.clipboardData.getData('text/plain')

See the bug: https://bugzilla.mozilla.org/show_bug.cgi?id=407983

Upvotes: 3

jejacks0n
jejacks0n

Reputation: 6102

Just wanted to provide more information about this -- because it's annoying.

First, firefox doesn't allow getting the clipboard content on paste (though it does support getting clipboard data in general -- for instance on drag/drop).

I started with the typical guess, right? Webkit allows this on paste:

event.clipboardData.getData('text/plain')

So one might expect that firefox might as well. Not true!

There's a way to accomplish the same thing however, and this is what makes me believe it's a dumb and outdated restriction. I mean, if I can get the pasted content anyway, why bother with the restriction? And if the user is pasting into an element that I have access to, great, I should have access to that pasted content if I know about the event at all -- I mean, why have the event if you can't get to the content being pasted?

So here's the solution for others -- this was submitted to a project of mine, and has migrated a bit over the years. It's using jQuery.

onPaste:

var hijacker = $('<div contenteditable="true" style="visibility:hidden"/>');
hijacker.appendTo(document.body).focus();
setTimeout(function() {
  console.debug(hijacker.html());
  hijacker.remove();
}, 1);

At the point that you can console.debug the html of the hijacker element you can do whatever you need with it. What gives Firefox? It's been several years now -- just provide it with clipboardData so I don't have to add hacky code like this.

Upvotes: 0

Related Questions