首页 > 解决方案 > javascript下载按钮而不是右键单击

问题描述

我正在尝试为 instagram 制作视频下载器,但每当我获取视频网址时,它不会下载,我必须右键单击并保存。有没有办法可以制作下载按钮而不是右键单击保存?

这是我的代码

$("#getMedia").click(getMedia);
var render = document.querySelector("#media");

function createMedia(data, type) {
    var media = document.createElement(type);
    media.id = "instagramMedia";
    media.src = data.content;
    media.setAttribute("class", "");
    media.width = $(render).width();
    
    if (type === "video") {
        media.controls = true;
        media.autoplay = true;      
    } 
    render.innerHTML = "";
    var downloadMsg = document.createElement("p");
    downloadMsg.setAttribute("class", "bg-success text-info");
    downloadMsg.innerText = "Right Click on the Media below to get Save Option!";

    render.appendChild(downloadMsg);
    render.appendChild(media);
}

function getMedia() {
    var url = $("#postUrl").val();
    if (url) {
        $.get(url, function (data) {
            render.innerHTML = data;
            var mediaWaitTimer = setTimeout(function () {
                var video = document.querySelector('meta[property="og:video"]');
                if (video) {
                    createMedia(video, "video");
                } else {
                    var img = document.querySelector('meta[property="og:image"]');
                    if (img) {
                        createMedia(img, "img");
                    } else {
                        document.body.innerHTML = body;
                        alert("Error extracting Instagram image / video.");
                    };
                }
                clearTimeout(mediaWaitTimer);
            }, 200);

        });

    } else {
        document.querySelector("#media").setAttribute("placeholder", "Invalid Address, Please Enter Proper Insagram Link");

    }
}

标签: javascripthtmldownload

解决方案


可能在您的函数中为您的可点击 html 元素设置download属性。createMedia

<a href="myvideo.mp4" download>Download</a>

供参考访问:https://www.w3schools.com/tags/att_a_download.asp


推荐阅读