Blog

画像のコピーを禁止する方法

2019/05/26

javascript JQuery

備忘録です。

参考サイト
テキストのドラッグ、画像のコピーを禁止して、記事をコピーさせない方法

右クリック禁止

html bodyに記述

<body oncontextmenu="return false;">

ドラッグを禁止

javascriptを記述

<script>
document.onselectstart = function(){ return false; };
document.onmousedown = function(){ return false; };
document.body.onselectstart = "return false;"
document.body.onmousedown = "return false;"
</script>

右クリック禁止と併用することで2重にプロテクトできます。

しかしながら実装したところselectが使えなくなりました。
onmousedownを無効にすることによりselectのダウン表示まで無効になってしまうのが原因でした。
そこで画像だけドラッグできない方法を見つけました。

$(function(){
  $('img').attr('onmousedown', 'return false');
  $('img').attr('onselectstart', 'return false');
  $('img').attr('oncontextmenu', 'return false');
 });

画像のコピーを禁止

透過gifを画像の上にのせることによりコピーを防ぐ方法です。

1 x 1pxのblank.gifを作成します。

下記をコピーしてdwImageProtector.jsを作成

<script>
jQuery.fn.protectImage = function(settings) {
 $("img[name=blank]").remove();
 settings = jQuery.extend({
 image: 'blank.gif', //パスを指定してください
 zIndex: 10
 }, settings);
return this.each(function() {
 var position = $(this).position();
 var height = $(this).height();
 var width = $(this).width();
 $('<img />').attr({
 width: width,
 height: height,
 src: settings.image,
 name : "blank"
}).css({
 top: position.top,
 left: position.left,
 position: 'absolute',
 zIndex: settings.zIndex
 }).appendTo('body')
 });
};
</script>

<head>~</head>内に記述

<script type="text/javascript" src="dwImageProtector.js"></script>
<script type="text/javascript">
$(window).bind('load', function() {
 $('img').protectImage();
 });
$(window).bind('resize', function() {
 $('img.protect').protectImage();
});
</script>

適用する画像にclassを付けます。

<img class="protect">

すべての画像に適用する場合は下記のようにします。

$('img').protectImage();

この方法だと画像をドラッグしてもblank.gifが保存されます。

カテゴリー

月間アーカイブ

MORE

ミュージシャンズ・プラザ

神社仏閣ホームーページ制作

ホームページ制作問合せ