探索,發現,愛好、學習,記錄,分享。
學海無涯,天涯若比鄰,三人行,必有我師。

html5视频文件防止下载

1、

$('#videoID').bind('contextmenu',function() { return false; });

2、

<style type="text/css">
    video::-webkit-media-controls-enclosure {
        overflow:hidden;
    }
    video::-webkit-media-controls-panel {
        width: calc(100% + 30px);
    }
</style>

Method three: add controlslist=”nodownload”

<video controls=”true” controlslist=”nodownload” width=”420″ height=”280″ poster=””></video>

Solutions/Answers:

Answer 1:

You can’t. That’s because that’s what browsers were designed to do: Serve content. But you can make it harder to download.

First thing’s first, you could disable the contextmenu event, aka “the right click”. That would prevent your regular skiddie from blatantly ripping your video by right clicking and Save As. But then they could just disable JS and get around this or find the video source via the browser’s debugger. Plus this is bad UX. There are lots of legitimate things in a context menu than just Save As.

You could also use custom video player libraries. Most of them implement video players that customize the context menu to your liking. So you don’t get the default browser context menu. And if ever they do serve a menu item similar to Save As, you can disable it. But again, this is a JS workaround. Weaknesses are similar to the previous option.

Another way to do it is to serve the video using HTTP Live Streaming. What it essentially does is chop up the video into chunks and serve it one after the other. This is how most streaming sites serve video. So even if you manage to Save As, you only save a chunk, not the whole video. It would take a bit more effort to gather all the chunks and stitch them using some dedicated software.

Another technique is to paint <video> on <canvas>. In this technique, with a bit of JavaScript, what you see on the page is a <canvas> element rendering frames from a hidden <video>. And because it’s a <canvas>, the context menu will use an <img>‘s menu, not a <video>‘s. You’ll get a Save Image As instead of a Save Video As.

You could also use CSRF tokens to your advantage. You’d have your sever send down a token on the page. You then use that token to fetch your video. Your server checks to see if it’s a valid token before it serves the video, or get an HTTP 401. The idea is that you can only ever get a video by having a token which you can only ever get if you came from the page, not directly visiting the video url.

At the end of the day, I’d just upload my video to a third-party video site, like YouTube or Vimeo. They have good video management tools, optimizes playback to the device, and they make efforts in preventing their videos from being ripped with zero effort on your end.

Answer 2:

This is a simple solution for those wishing to simply remove the right-click “save” option from the html5 videos

$(document).ready(function(){
   $('#videoElementID').bind('contextmenu',function() { return false; });
});

Answer 3:

Simple answer,

YOU CAN’T

If they are watching your video, they have it already

You can slow them down but can’t stop them.

Answer 4:

Yes, you can do this in three steps:


  1. Place the files you want to protect in a subdirectory of the directory where your code is running.

    www.xxx.com/player.html
    www.xxx.com/videos/video.mp4

  2. Save a file in that subdirectory named “.htaccess” and add the lines below.

    www.xxx.com/videos/.htaccess

    #Contents of .htaccess
    
    RewriteEngine on
    RewriteCond %{HTTP_REFERER} !^http://xxx.com/.*$ [NC]
    RewriteCond %{HTTP_REFERER} !^http://www.xxx.com/.*$ [NC]
    RewriteRule .(mp4|mp3|avi)$ - [F]
    

Now the source link is useless, but we still need to make sure any user attempting to download the file cannot be directly served the file.

  1. For a more complete solution, now serve the video with a flash player (or html canvas) and never link to the video directly. To just remove the right click menu, add to your HTML:
    <body oncontextmenu="return false;">
    

The Result:

www.xxx.com/player.html will correctly play video, but if you visit www.foo.com/videos/video.mp4:

Error Code 403: FORBIDDEN

This will work for direct download, cURL, hotlinking, you name it.

This is a complete answer to the two questions asked and not an answer to the question: “can I stop a user from downloading a video they have already downloaded.”

Answer 5:

The best way that I usually use is very simple, I fully disable context menu in the whole page, pure html+javascript:

 <body oncontextmenu="return false;">

That’s it! I do that because you can always see the source by right click.
Ok, you say: “I can use directly the browser view source” and it’s true but we start from the fact that you CAN’T stop downloading html5 videos.

Answer 6:

As a client-side developer I recommend to use blob URL,
blob URL is a client-side URL which refers to a binary object

<video id="id" width="320" height="240"  type='video/mp4' controls  > </video>

in HTML leave your video src blank,
and in JS fetch the video file using AJAX, make sure the response type is blob

window.onload = function() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'mov_bbb.mp4', true);
    xhr.responseType = 'blob'; //important
    xhr.onload = function(e) {
        if (this.status == 200) {
            console.log("loaded");
            var blob = this.response;
            var video = document.getElementById('id');
            video.oncanplaythrough = function() {
                console.log("Can play through video without stopping");
                URL.revokeObjectURL(this.src);
            };
            video.src = URL.createObjectURL(blob);
            video.load();
        }
    };
    xhr.send();
}

Note: This method is not recommended for large file

EDIT

  • Use cross-origin blocking for avoiding direct downloading
  • if the video is delivered by an API Use different method (PUT/POST) instead of ‘GET’

Answer 7:

PHP sends the html5 video tag together with a session where the key is a random string and the value is the filename.

ini_set('session.use_cookies',1);
session_start();
$ogv=uniqid(); 
$_SESSION[$ogv]='myVideo.ogv';
$webm=uniqid(); 
$_SESSION[$webm]='myVideo.webm';
echo '<video autoplay="autoplay">'
    .'<source src="video.php?video='.$ogv.' type="video/ogg">'
    .'<source src="video.php?video='.$webm.' type="video/webm">'
    .'</video>'; 

Now PHP is asked to send the video. PHP recovers the filename; deletes the session and sends the video instantly. Additionally all the ‘no cache’ and mime-type headers must be present.

ini_set('session.use_cookies',1);
session_start();
$file='myhiddenvideos/'.$_SESSION[$_GET['video']];
$_SESSION=array();
$params = session_get_cookie_params();
setcookie(session_name(),'', time()-42000,$params["path"],$params["domain"],
                                         $params["secure"], $params["httponly"]);
if(!file_exists($file) or $file==='' or !is_readable($file)){
  header('HTTP/1.1 404 File not found',true);
  exit;
  }
readfile($file);
exit:

Now if the user copy the url in a new tab or use the context menu he will have no luck.

Answer 8:

You can at least stop the the non-tech savvy people from using the right-click context menu to download your video. You can disable the context menu for any element using the oncontextmenu attribute.

oncontextmenu="return false;"

This works for the body element (whole page) or just a single video using it inside the video tag.

<video oncontextmenu="return false;" controls>...</video>

Answer 9:

We ended up using AWS CloudFront with expiring URLs. The video will load, but by the time the user right clicks and chooses Save As the video url they initially received has expired. Do a search for CloudFront Origin Access Identity.

Producing the video url requires a key pair which can be created in the AWS CLI. FYI this is not my code but it works great!

$resource = 'http://cdn.yourwebsite.com/videos/yourvideourl.mp4';
$timeout = 4;

//This comes from key pair you generated for cloudfront
$keyPairId = "AKAJSDHFKASWERASDF";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition" {"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';     

//Read Cloudfront Private Key Pair
$fp=fopen("/absolute/path/to/your/cloudfront_privatekey.pem","r"); 
$priv_key=fread($fp,8192); 
fclose($fp); 

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
    echo "<p>Failed to load private key!</p>";
    return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
    echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
    return;
}

//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

return '<div class="videowrapper" ><video autoplay controls style="width:100%!important;height:auto!important;"><source src="'.$url.'" type="video/mp4">Your browser does not support the video tag.</video></div>';

Answer 10:

+1 simple and cross-browser way:
You can also put transparent picture over the video with css z-index and opacity.
So users will see “save picture as” instead of “save video” in context menu.

Answer 11:

The

<body oncontextmenu="return false;"> 

no longer works. Chrome and Opera as of June 2018 has a submenu on the timeline to allow straight download, so user doesn’t need to right click to download that video. Interestingly Firefox and Edge don’t have this …

Answer 12:

Using a service such as Vimeo: Sign in Vimeo > Goto Video > Settings > Privacy > Mark as Secured, and also select embed domains. Once the embed domains are set, it will not allow anyone to embed the video or display it from the browser unless connecting from the domains specified. So, if you have a page that is secured on your server which loads the Vimeo player in iframe, this makes it pretty difficult to get around.

Answer 13:

First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.

A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.

You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well – you should.

You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that.". As suggested in this answer.

This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.

Here is a CSS trick you could use:

video {
    pointer-events: none;
}

CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls cannot be enabled either, in other words they must be set to false. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video tag then this is a feasible option.

controls also has a download button so using it is not such a good idea either.

Here is a JSFiddle example.


If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).

From TxRegex answer:

<video oncontextmenu="return false;" controls>
    <source type="video/mp4" id="video">
</video>

Now add the video via JavaScript:

document.getElementById("video").src = "https://www.xxx.com/html/mov_bbb.mp4";

Functional JSFiddle


Another way to prevent right click involves using the embed tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:

<embed src="https://www.xxx.com/html/mov_bbb.mp4"></embed>

Answer 14:

    $(document).ready(function(){

$(‘#videoId’).bind(‘contextmenu’,function() { return false; });

})

版權聲明:本文采用知識共享 署名4.0國際許可協議 [BY-NC-SA] 進行授權
轉載事宜:如需轉載需徵得應允,轉載必須注明來源於本站的信息。
文章名称:《html5视频文件防止下载》
文章链接:https://www.thefreesky.com/blog/26286.html
本站資源僅供個人學習交流,請於下載後24小時內刪除,不允許用於商業用途,否則法律問題自行承擔。

評論 抢沙发