加载图片时加上请求头,Web Components 实现

私密图片,请求图片时需要鉴权

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2019 9月 [工具] TreeJS 在线编辑器: https://threejs.org/editor/[ht...
    halber阅读 2,123评论 0 2
  • 前言 不知不觉,2019年即将接近尾声,现有前端三大框架也各自建立着自己的生态、自己的使用群体。从angular1...
    Kaku_fe阅读 2,828评论 0 19
  • showcase14: https://github.com/FE-star/showcase14 showcas...
    hha123阅读 176评论 0 0
  • 渐变的面目拼图要我怎么拼? 我是疲乏了还是投降了? 不是不允许自己坠落, 我没有滴水不进的保护膜。 就是害怕变得面...
    闷热当乘凉阅读 4,350评论 0 13
  • 夜莺2517阅读 127,761评论 1 9