私密图片,请求图片时需要鉴权
import { hex_md5 } from 'md5';
function getCookie(name, defaultValue) {
let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg)) return unescape(arr[2]);
else return defaultValue;
}
let requestImage = function (url, element) {
let request = new XMLHttpRequest();
request.responseType = 'blob';
request.open('get', url, true);
let token = getCookie("token") || "",
timestamp = String((new Date()).getTime()),
securt = "your securt",
sign = hex_md5(`AUTH-TIMESTAMP=${timestamp}&AUTH-TOKEN=${token}#${securt}`);
request.setRequestHeader('AUTH-SIGN', sign);
request.setRequestHeader('AUTH-TIMESTAMP', timestamp);
request.setRequestHeader('AUTH-TOKEN', token);
request.onreadystatechange = e => {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
if (request.response.type == 'image/jpeg' || request.response.type == 'image/png' || request.response.type == 'image/jpg') {
element.src = URL.createObjectURL(request.response);
element.style.display = "block";
// element.part = "native";
element.onload = () => {
URL.revokeObjectURL(element.src);
}
} else {
element.src = "";
element.style.display = "none";
}
} else {
element.src = "";
element.style.display = "none";
}
};
request.send(null);
}
class AuthImg extends HTMLElement {
constructor() {
super();
this.img = new Image();
const shadow = this.attachShadow({ mode: 'open' });
// shadow.innerHTML = ``; // 添加dom结构
shadow.appendChild(this.img);
}
// 监听属性修改
static get observedAttributes() { return ['auth-src', 'style', 'class']; }
// 生命周期钩子函数
connectedCallback() {
// if(this.img == null){
// this.img = new Image();
// const shadow = this.attachShadow({ mode: 'open'});
// shadow.appendChild(this.img);
// }
requestImage(this.getAttribute('auth-src'), this.img);
if (this.getAttribute("style")) {
this.img.setAttribute("style", this.getAttribute("style"));
}
if (this.getAttribute("class")) {
this.img.className = this.getAttribute("class");
}
}
attributeChangedCallback(name, oldValue, newValue) {
if (name == 'auth-src' && (oldValue !== null && newValue !== oldValue)) {
requestImage(this.getAttribute('auth-src'), this.img);
} else if (name == 'style') {
this.img.setAttribute("style", this.getAttribute("style"));
} else if (name == 'class') {
this.img.className = this.getAttribute("class");
}
}
disconnectedCallback() {
// const shadow = this.attachShadow({ mode: 'open'});
// shadow.removeChild(this.img);
this.img.src = '';
}
}
window.customElements.define('auth-img', AuthImg); // 定义自定义标签名称
使用方法
<img is="auth-img" auth-src="xxx.jpg">
官方文档:https://developers.google.cn/web/fundamentals/web-components/
参考文章:
https://github.com/linpenghui958/note/blob/master/WebComponents.md
https://zhuanlan.zhihu.com/p/150268517?from_voters_page=true