IT박스

HTML5 비디오를 다운로드하지 못하게합니까 (오른쪽 클릭 저장)?

itboxs 2020. 6. 9. 22:21
반응형

HTML5 비디오를 다운로드하지 못하게합니까 (오른쪽 클릭 저장)?


클라이언트가 비디오를 다운로드하지 못하도록 브라우저의 오른쪽 클릭 메뉴에서 "다른 이름으로 비디오 저장 ..."을 비활성화하려면 어떻게해야합니까?

클라이언트가 파일 경로에 직접 액세스하지 못하게하는보다 완벽한 솔루션이 있습니까?


당신은 할 수 없습니다 . 이는 브라우저가 디자인 한 것이기 때문입니다 . 컨텐츠 제공 . 그러나 다운로드하기가 더 어려워 질 수 있습니다 .

우선 , "오른쪽 클릭" 이라는 이벤트를 비활성화 있습니다. 그러면 마우스 오른쪽 버튼을 클릭하고 다른 이름으로 저장을 클릭하여 일반 스키드가 비디오를 찢어 버리는 것을 방지 할 수 있습니다. 그러나 그들은 JS를 비활성화 하고이 문제를 해결하거나 브라우저의 디버거를 통해 비디오 소스를 찾을 수 있습니다. 게다가 이것은 나쁜 UX입니다. 상황에 맞는 메뉴에는 다른 이름으로 저장보다 합법적 인 것들이 많이 있습니다.contextmenu

사용자 정의 비디오 플레이어 라이브러리를 사용할 수도 있습니다. 대부분은 원하는대로 상황에 맞는 메뉴를 사용자 정의하는 비디오 플레이어를 구현합니다. 따라서 기본 브라우저 컨텍스트 메뉴가 표시되지 않습니다. 다른 이름으로 저장과 비슷한 메뉴 항목을 제공하는 경우 해당 기능을 비활성화 할 수 있습니다. 그러나 이것은 JS 해결 방법입니다. 약점은 이전 옵션과 유사합니다.

또 다른 방법은 HTTP Live Streaming을 사용하여 비디오를 제공하는 것입니다 . 그것이 본질적으로하는 일은 비디오를 덩어리로 자르고 차례로 제공하는 것입니다. 이것이 대부분의 스트리밍 사이트가 비디오를 제공하는 방법입니다. 따라서 다른 이름으로 저장을 관리하더라도 전체 비디오가 아닌 청크 만 저장합니다. 모든 청크를 수집하고 일부 전용 소프트웨어를 사용하여 스티치하는 데 약간의 노력이 필요합니다.

또 다른 기술은에 페인트 <video>하는 것<canvas> 입니다. 이 기법에서는 약간의 JavaScript를 사용하여 페이지에 표시되는 <canvas>요소는 hidden에서 프레임을 렌더링 하는 요소 <video>입니다. 그리고이이기 때문에 <canvas>상황에 맞는 메뉴는 <img>의 메뉴가 아닌의 메뉴를 사용합니다 <video>. 다른 이름으로 비디오 저장 대신 다른 이름으로 이미지 저장을 얻게됩니다.

CSRF 토큰 을 유리하게 사용할 수도 있습니다 . 서버에서 서버로 토큰을 보내도록해야합니다. 그런 다음 해당 토큰을 사용하여 비디오를 가져옵니다. 서버는 비디오를 제공하기 전에 유효한 토큰인지 확인하거나 HTTP 401을 얻습니다 . 아이디어는 비디오 URL을 직접 방문하지 않고 페이지에서 온 경우에만 얻을 수있는 토큰을 가져서 만 비디오를 얻을 수 있다는 것입니다.

하루가 끝나면 YouTube 또는 Vimeo와 같은 타사 비디오 사이트에 비디오를 업로드합니다. 그들은 훌륭한 비디오 관리 도구를 가지고 있으며, 장치 재생을 최적화하며, 노력을 기울이지 않고도 비디오가 찢어지지 않도록 노력합니다.


이것은 html5 비디오에서 마우스 오른쪽 버튼 클릭 "저장"옵션을 간단히 제거하려는 사람들을위한 간단한 솔루션입니다.

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

간단한 대답,

당신은 할 수 없습니다

그들이 당신의 비디오를보고 있다면, 그들은 이미 가지고 있습니다

속도를 늦출 수는 있지만 멈출 수는 없습니다.


예, 세 단계로 수행 할 수 있습니다.


  1. 보호하려는 파일을 코드가 실행중인 디렉토리의 서브 디렉토리에 두십시오.

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

  2. ".htaccess"라는 하위 디렉토리에 파일을 저장하고 아래 행을 추가하십시오.

    www.foo.com/videos/.htaccess

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

이제 소스 링크는 쓸모 가 없지만 파일을 다운로드하려는 모든 사용자에게 직접 파일을 제공 할 수 없도록해야합니다.

  1. 보다 완벽한 솔루션을 얻으 려면 이제 플래시 플레이어 (또는 html 캔버스)를 사용하여 비디오를 제공하고 비디오에 직접 연결하지 마십시오. 마우스 오른쪽 버튼 클릭 메뉴를 제거하려면 HTML에 추가하십시오.

    <body oncontextmenu="return false;">
    


결과:

www.foo.com/player.html 은 비디오를 올바르게 재생 하지만 www.foo.com/videos/video.mp4를 방문하는 경우 :

오류 코드 403 : FORBIDDEN


이것은 직접 다운로드, cURL, 핫 링크에 사용할 수 있습니다.

이것은 두 가지 질문에 대한 완전한 대답이며 질문에 대한 대답은 아닙니다. "사용자가 이미 다운로드 한 비디오를 다운로드하지 못하게 할 수 있습니까?"


내가 일반적으로 사용하는 가장 좋은 방법은 매우 간단합니다. 전체 페이지에서 컨텍스트 메뉴를 완전히 비활성화합니다. 순수한 html + javascript :

 <body oncontextmenu="return false;">

그게 다야! 마우스 오른쪽 버튼을 클릭하면 항상 소스를 볼 수 있기 때문에 그렇게합니다.
"브라우저보기 소스를 직접 사용할 수 있습니다"라고 말하지만 사실은 비디오 다운로드를 중단 없다는 사실에서 시작 html5합니다.


클라이언트 측 개발자는 BLOB URL을 사용하는 것이 좋습니다. Blob URL은 이진 객체를 나타내는 클라이언트 측 URL입니다.

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

HTML에서 비디오를 src비워 두고 JS에서 AJAX를 사용하여 비디오 파일을 가져옵니다. 응답 유형이 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();
}

참고 :이 방법은 큰 파일에는 권장되지 않습니다

편집하다

  • 직접 다운로드를 피하기 위해 교차 출처 차단 사용

  • 동영상이 API로 제공되는 경우 'GET'대신 다른 방법 (PUT / POST)을 사용하십시오.


PHP는 키가 임의 문자열이고 값이 파일 이름 인 세션과 함께 html5 비디오 태그를 보냅니다.

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>'; 

이제 PHP는 비디오를 보내도록 요청받습니다. PHP는 파일 이름을 복구합니다. 세션을 삭제하고 비디오를 즉시 보냅니다. 또한 모든 '캐시 없음'및 MIME 유형 헤더가 있어야합니다.

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.


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>

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>';

+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.


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 ...


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.


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.w3schools.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.w3schools.com/html/mov_bbb.mp4"></embed>

Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)

I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.

Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.


웹 소켓을 통해 비디오를 스트리밍하는 것은 프레임을 스트리밍하고 캔버스에 그리는 것과 같이 실행 가능한 옵션입니다.

JavaScript를 사용하여 웹 소켓을 통한 비디오 스트리밍

클라이언트가 비디오를 획득하고 "비디오를 다른 이름으로 저장 ..."마우스 오른쪽 단추 클릭 상황에 맞는 메뉴 옵션 (오버 킬?!)을 사용하여 문제를 해결하는 데 도움이되는 다른 수준의 보호 기능을 제공한다고 생각합니다.


내가 한 일은 다음과 같습니다.

function noRightClick() {
      alert("You cannot save this video for copyright reasons. Sorry about that.");
}
    <body oncontextmenu="noRightClick();">
    <video>
    <source src="http://calumchilds.com/videos/big_buck_bunny.mp4" type="video/mp4">
    </video>
    </body>
이것은 이미지, 텍스트 및 거의 모든 것에 대해서도 작동합니다. 그러나 바로 가기 키를 통해 "검사"및 "소스보기"도구에 계속 액세스 할 수 있습니다. (맨 위의 답변에서 알 수 있듯이 완전히 멈출 수는 없습니다.) 그러나 장애물을 막기 위해 장벽을 세우려고 시도 할 수 있습니다.


다음과 같이 상황에 맞는 메뉴를 숨겨서 그렇게 쉽게 만들 수는 없습니다.

<video oncontextmenu="return false;"  controls>
  <source src="https://yoursite.com/yourvideo.mp4" >
</video>

@Clayton-Graul had what I was looking for, except I needed the CoffeeScript version for a site using AngularJS. Just in case you need that too, here's what you put in the AngularJS controller in question:

    # This is how to we do JQuery ready() dom stuff
    $ ->
        # let's hide those annoying download video options.
        # of course anyone who knows how can still download
        # the video, but hey... more power to 'em.
        $('#my-video').bind 'contextmenu', -> 
            false

"strange things are afoot at the circle k" (it's true)

참고URL : https://stackoverflow.com/questions/9756837/prevent-html5-video-from-being-downloaded-right-click-saved

반응형