基於mutation的自定義指令以監聽用戶使用f12修改dom

昨天寫了功能後,就又封了一個指令,可以直接應用於ui框架的input組件上

貼貼:

preventChange/index.js 
export const preventChange = {
  inserted(el, binding) {
    const elTag = el.tagName.toLowerCase();
    // 獲取當前dom下類型爲password的input標籤
    const passwordInput = el.querySelector(`${elTag}  input[type="password"]`);
    // if has psdipt
    if (passwordInput) {
      const config = {
        attributes: true, // 監聽到修改屬性時觸發
        childList: false,
        subtree: false
      };
      // 以上述配置開始觀察目標節點
      const observeInstance = new MutationObserver(mutationsList => {
        for (let mutation of mutationsList) {
          if (mutation.type === "attributes") {
            passwordInput.type = "password";
            // 停止監聽,一定要有這一步,否則頁面將直接卡死!
            observeInstance.disconnect();
            // 隨即重新監聽
            observeInstance.observe(passwordInput, config);
          }
        }
      });
      observeInstance.observe(passwordInput, config); // 監聽paswd
      passwordInput.__mutationObserver = observeInstance;
    }
  },
  unbind(el) {
    const elTag = el.tagName.toLowerCase();
    const passwordInput = el.querySelector(`${elTag}  input[type="password"]`);
    if (passwordInput) {
      const observer = passwordInput.__mutationObserver;
      if (observer) {
        //  observer.disconnect && observer.disconnect();
         delete passwordInput.__mutationObserver;
      }
    }
  }
};

使用:

<el-input v-model="input" type="password" v-preventChange placeholder="請輸入內容"></el-input>

其實還可以再進一步判斷當前dom是不是input[type="password"],但K桑實在是太懶了
此自定義指令作用爲:屏蔽用戶打開f12試圖修改密碼輸入框以查看明文密碼。 至於註冊是全局還是局部,諸君請便。

以上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章