function clickLink(link) {
var cancelled = false;
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0,
false, false, false, false,
0, null);
cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
if (!cancelled) {
window.location = link.href;
}
}
for (var i = 0; i < links.length; i++) {
var x=links[i];
if(x.href.indexOf('download.mp4') > -1) {
console.log(x.href); x.click();
}
}
for (var i = 0; i < links.length; i++) {
var x=links[i];
if(x.href.indexOf('download.mp4') > -1) {
console.log(x.href); clickLink(x);
}
}
With above code the purpose was to download all video links on one page. Although console log contains all the links I want only one link really gets downloaded. There are no errors or warnings, how can I achieve this ? Also tried without window.location line, no luck...
following worked out now:
function JustclickLink(link) {
var cancelled = false;
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0,
false, false, false, false,
0, null);
cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
if (!cancelled) {
window.open(link.href,'_blank');
}
}
for (var i = 0; i < links.length; i++){
var x=links[i];
if(x.href.indexOf('download.mp4') > -1){
console.log(x.href); JustclickLink(x);
}
}
Here's a jquery alternative to what you seek. Window.open should be used for multiple downloads, as window.location will trigger only once in the code run.
$('#foo').on('click', function() {
window.open($(this).attr("href"),'_blank');
});
$('#foo').trigger('click');