2011-08-03 197 views
16

I have an HTML 5 app that runs on mobile devices including the iPad. I want to create a link to a non-HTML file, and have the proper application open to handle the file. The files are .acsm files, to be opened in Bluefire.Cuál es la diferencia entre <a href="url"> and window.location = "url" on iOS?

If I create the link as a simple <a href="url"> tag, it works.

If instead I use Javascript to set the window.location, it doesn't work. The iPad pops an alert that says, "Download failed: This file cannot be downloaded".

I've experimented with other file types, and haven't found anything conclusive. What's the difference between the simple link and the Javascript technique? Can I make the Javascript code do the same thing as the link?

In case the specific Javascript details matter, I do it like this with jQuery:

$('.native-launch').live('click', function (evobj) { 
    var there = $(evobj.target).attr('href'); 
    window.location.href = there; 
    return false; 
}); 

and the HTML looks like:

<span class="catalog-list-button native-launch" href="url">Read in another app</span> 

(Note that this is a span with an href, I can change the HTML if that would help.)

+1

¿Ha intentado usar 'window.open'? – kei

+0

@kei: ¡gran idea! No funciona :(Hace lo mismo que el código Javascript: "Error de descarga" –

+0

¿Qué pasa si usted hizo un iFrame que cargó la URL? '' –

Respuesta

1

It seems like a Safari bug to me. If you write window.location : Safari is expecting an html file or any type of file it can actualy display.

Whereas when you click a link it reads the content-type and then decide to open it in the same window or open an application for it.

I think you should try to open a popup window with the url. It should theoretically work.

+0

Si con "ventana emergente" te refieres a window.open, lo probé y no sirve de nada. –

0

I would think a link was better in case some type of screen reader was trying to parse your page. If your navigation was in javascript, something like that would fail to tell visually impaired users what's going on.

Btw, instead of return false; from your event handler. do evobj.preventDefault(), it's the preferred way to stop bubbling for the event.

+0

gracias por la sugerencia sobre preventionDefault, pero si pongo eso y elimino mi "return false", el comportamiento cambia, parece que el evento sigue burbujeando hacia el div que lo rodea. –

+0

Si lo está manejando desde otros elementos de nivel superior, puede usar 'event.isDefaultPrevented()' para verificar si debe actuar sobre él. Aunque no suena como eso en tu caso ... – Milimetric

1

With the JS-function window.location the browser want to open the file with the Browser and not with any other program. But with the A-Tag you link to something. This can be any file. If the browser didn't know the typ of the file the browser alert a popup for download the file. If the file is for example a HTML-File the browser open the file and show it.

For downloading a File with JS here is a link.

4

crear una nueva etiqueta y haga clic usando jQuery:

$("<a />").attr("href", there).click(); 

la una etiqueta en este caso no se añadirá a DOM, solamente se utilizarán para simular el clic.

+0

Hmm, idea interesante. Cuando intento esto, parece que el evento de clic aparece a través de otros divs, lo que desencadena eventos en el camino. –

+0

sí, he cometido un error. antes de que hubiera $ ("a") que seleccionara todos los enlaces en la página y haga clic en ellos. – memical

0

Según el HTML5 spec, el elemento span solo puede tener el global attributes, que no incluye href. Por lo tanto, el valor obtenido del atributo puede estar mal formado o ser incompatible con el tipo aceptado por window.location.href. No estoy seguro de si esto podría estar relacionado con el problema.

¿Intentó asignar una cadena constante como window.location.href = "http://example.com/file"?

5

Pruebe window.open, pasando en "_self" como el nombre de la ventana de destino.

window.open(there, "_self"); 

El uso de "_self" es la parte crítica aquí, de lo contrario, el bloqueador de ventanas emergentes lo interceptaría. Yo probaría esto, pero no tengo un enlace a un archivo acsm.

Editar: Otros dos ideas:

agregar un formulario a su página con un método de "GET" y una acción de su archivo ACSM. Excluya los campos del formulario a menos que se asignen adecuadamente a su URL.

<form id="acsm" method="GET" action="http://myserver.com/myfile.acsm"></form> 

A continuación, sólo enviar su formulario con form.submit():

document.forms.acsm.submit(); 

Y la otra idea: Crear una página en el servidor que tiene un lado del servidor redirigir a su archivo ACSM. Luego simplemente use el location.href = url habitual en esa página del servidor.

+0

Una idea interesante, no cambió el comportamiento. –

+0

Oh, bueno. Valió la pena el intento. – gilly3

+0

Estas son más buenas ideas. No sé si aún funcionan, pero parecen prometedores. –

0

Si esto es un error con iOS, simule un clic en un enlace. A diferencia de la solución de memical, esto no será una burbuja:

var a = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); 
a.href = your_url_here; 
var click = document.createEvent("Event"); 
click.initEvent("click", false /*bubbles*/, true /*cancellable*/); 
a.dispatchEvent(click); 
Cuestiones relacionadas