A continuación se describe la mejor practica para utilizar los datos a ser arrastrado.
Arrastramdo Texto
Al arrastrar el texto, utilice el texto / texto normal. Los datos deben ser la cadena de arrastre. Por ejemplo:
event.dataTransfer.setData("text/plain", "This is text to drag")
Arrastrar texto en cuadros de texto y las selecciones de las páginas web se realiza de forma automática, por lo que no es necesario para manejar dragging.
Se recomienda que siempre se agrega datos del tipo text/plain
como un mensaje para las aplicaciones o los destinos que no soportan otros tipos, a menos que no hay alternativa de texto lógico. Siempre agregue el tipo de texto sin formato pasado, ya que es el menos específico.
En códigos más viejo, encontrara text/unicode o el tipo Text.Estos equivalen text/plain,que guardara y recibia los datos del texto plano en ese lugar.
Arrastrando Enlaces
Los enlaces deben incluir los datos de los dos tipos, el primero debe ser URL utilizando el tipo text/uri-list,y el segundo es URL utilizando el tipo text/plain. Ambos tipos deben utilizar los mismos datos, la URL del enlace. Por ejemplo:
var dt = event.dataTransfer; dt.setData("text/uri-list", "https://www.mozilla.org"); dt.setData("text/plain", "https://www.mozilla.org");
Es constumbre, establecer el tipo text/plain de ultimo, , ya que es menos específico que el tipo de URI.
Note que el tipo de URL uri-list es con una "i", no una "L"
Note that the URL type is uri-list
with an 'I', not with an 'L'.
To drag multiple links, you can also separate each link with a linebreak. A line that begins with a number sign (#) is a comment and should not be considered a valid URL. You can use a comment to indicate the purpose of a link, or to hold the title associated with a link. The text/plain
version of the drag data should include all links but should not include the comments.
For example:
https://www.mozilla.org #A second link https://www.xulplanet.com
This sample text/uri-list
data contains two links and a comment.
When retrieving a dropped link, you should ensure you handle the case where multiple links may have been dragged, and any comments that appear in the data. For convenience, the special type URL
may be used to refer to the first valid link within the data for the text/uri-list
type. You should not add data using the URL
type; attempting to do so will just set the value of the text/uri-list
type instead.
var url = event.dataTransfer.getData("URL");
You may also see data using the text/x-moz-url
type which is a Mozilla specific type. If it appears, it should be used before the text/uri-list
type. It holds the URL of the link followed by the title of the link, separated by a linebreak. For example:
https://www.mozilla.org Mozilla https://www.xulplanet.com XUL Planet
Dragging HTML and XML
HTML content may use the text/html
type. The data for this type should be the serialized HTML to drag. For instance, it would be suitable to set the data value for this type to the value of the innerHTML
property of an element.
XML content may use the text/xml
type, but you should ensure that the data value is well-formed XML.
You may also include a plain text representation of the HTML or XML data using the text/plain
type. The data should be just the text and should not include any of the source tags or attributes. For instance:
var dt = event.dataTransfer; dt.setData("text/html", "Hello there, <strong>stranger</strong>"); dt.setData("text/plain", "Hello there, stranger");
Dragging Files
A local file is dragged using the application/x-moz-file
type with a data value that is an nsIFile object. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAt method to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAt method.
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
If possible, you may also include the file URL of the file using both the text/uri-list
and/or text/plain
types. These types should be added last so that the more specific application/x-moz-file
type has higher priority.
Multiple files will be received during a drop as mutliple items in the data transfer. See Dragging and Dropping Multiple Items for more details about this.
The following example shows how to create an area for receiving dropped files:
<listbox ondragenter="return checkDrag(event)" ondragover="return checkDrag(event)" ondrop="doDrop(event)"/> <script> function checkDrag(event) { return event.dataTransfer.types.contains("application/x-moz-file"); } function doDrop(event) { var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0); if (file instanceof Components.interfaces.nsIFile) event.currentTarget.appendItem(file.leafName); } </script>
In this example, the event returns false only if the data transfer contains the application/x-moz-file
type. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceof
operator is used here as the mozGetDataAt method will return an nsISupports
that needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.
Dragging Images
Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-list
type as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.
As with other links, the data for the text/plain
type should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plain
data in this situation.
In chrome or other privileged code, you may also use the image/jpeg
, image/png
or image/gif
types, depending on the type of image. The data should be an object which implements the nsIInputStream interface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.
You should also include the application/x-moz-file
type if the image is located on disk. In fact, this a common way in which image files are dragged.
It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpeg
should come first, followed by the application/x-moz-file
type. Next, you should set the text/uri-list
data and finally the text/plain
data. For example:
var dt = event.dataTransfer; dt.mozSetDataAt("image/png", stream, 0); dt.mozSetDataAt("application/x-moz-file", file, 0); dt.setData("text/uri-list", imageurl); dt.setData("text/plain", imageurl);
Note that the mozGetDataAt method is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.
Dragging Nodes
Nodes and elements in a document may be dragged using the application/x-moz-node
type. This data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.
You should always include a plain text alternative for the node.
Dragging Custom Data
You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.
Dragging files to an operating system folder
There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data flavor "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:
// currentEvent is a given existing drag operation event currentEvent.dataTransfer.setData("text/x-moz-url", URL); currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL); currentEvent.dataTransfer.setData("application/x-moz-file-promise-filename", leafName); currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise', new dataProvider(success,error), 0, Components.interfaces.nsISupports); function dataProvider(){} dataProvider.prototype = { QueryInterface : function(iid) { if (iid.equals(Components.interfaces.nsIFlavorDataProvider) || iid.equals(Components.interfaces.nsISupports)) return this; throw Components.results.NS_NOINTERFACE; }, getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) { if (aFlavor == 'application/x-moz-file-promise') { var urlPrimitive = {}; var dataSize = {}; aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize); var url = new String(urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString)); console.log("URL file orignal is = " + url); var namePrimitive = {}; aTransferable.getTransferData('application/x-moz-file-promise-filename', namePrimitive, dataSize); var name = new String(namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString)); console.log("target filename is = " + name); var dirPrimitive = {}; aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize); var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile); console.log("target folder is = " + dir.path); var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(dir.path); file.appendRelativePath(name); console.log("output final path is =" + file.path); // now you can write or copy the file yourself... } } }