Eyedropper API本地正常,部署服务器后报错:EyeDropper未定义
图片取色器Eyedropper API部署后报错问题解决
问题描述
开发一款基于Eyedropper API的图片取色器,在localhost本地环境运行正常,但部署到服务器后控制台抛出错误:Uncaught ReferenceError: EyeDropper is not defined,相关代码如下:
if (!window.EyeDropper) { alert("Your browser does not support Image Color Picker feature"); } const eyeDropper = new EyeDropper(); const pickerBtn = document.querySelector(".open-picker"); const toast = document.getElementById('toast'); const result = document.querySelector(".color_code_field"); function showToast(message) { toast.innerHTML = ` <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#fff" class="toast_icon"> <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> ${message} `; toast.classList.remove('hide'); setTimeout(() => { toast.classList.add('hide'); }, 3000); } imgInput.addEventListener("change", function() { const file = this.files[0]; if (!file) return; const reader = new FileReader(); reader.addEventListener("load", function() { imgPreview.src = this.result; }); reader.readAsDataURL(file); }); pickerBtn.addEventListener("click", function() { eyeDropper .open() .then((res) => { result.value = `${res.sRGBHex}`; }) .catch((err) => { console.log("User canceled the selection."); }); });
解决方案
1. 核心原因:服务器未使用HTTPS环境
Eyedropper API属于浏览器的安全上下文限制API,仅允许在HTTPS协议或localhost(本地开发例外)环境下运行。部署到服务器后如果使用HTTP协议,浏览器会禁用该API,导致EyeDropper is not defined错误。
2. 解决步骤
切换服务器到HTTPS环境:
为服务器配置SSL证书(生产环境使用正规CA颁发的证书,测试环境可使用自签名证书),确保网站通过HTTPS协议访问,这样浏览器才会允许使用Eyedropper API。修复兼容性检查逻辑:
原代码中仅做了window.EyeDropper的存在性检查,但后续创建实例的代码未包裹在条件判断内,即使不支持也会执行new EyeDropper()导致报错。修改代码如下:
if (!window.EyeDropper) { alert("Your browser does not support Image Color Picker feature"); } else { const eyeDropper = new EyeDropper(); const pickerBtn = document.querySelector(".open-picker"); const toast = document.getElementById('toast'); const result = document.querySelector(".color_code_field"); function showToast(message) { toast.innerHTML = ` <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="#fff" class="toast_icon"> <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> ${message} `; toast.classList.remove('hide'); setTimeout(() => { toast.classList.add('hide'); }, 3000); } imgInput.addEventListener("change", function() { const file = this.files[0]; if (!file) return; const reader = new FileReader(); reader.addEventListener("load", function() { imgPreview.src = this.result; }); reader.readAsDataURL(file); }); pickerBtn.addEventListener("click", function() { eyeDropper .open() .then((res) => { result.value = `${res.sRGBHex}`; }) .catch((err) => { console.log("User canceled the selection."); }); }); }
这样当环境不支持Eyedropper API时,只会触发alert提示,不会执行后续报错代码。
内容的提问来源于stack exchange,提问作者Maaz A.
相关产品推荐
相关产品推荐

