摘录web前端记住用户名密码

大前端记住用户名密码,方法有很多的,我今天采用的是前端indexDB来存放

前端页面使用框架vue搭建

首先,创建indexDB, 通过window.indexedDB.open来打开数据,若数据库不存在,则会创建一个,当然,参数还有另一个参数version来表示当前数据库的版本号,比如:let db= window.indexedDB.open('user',1);第二个参数就是版本号,版本号只能是正整数。

其中会有几个方法钩子,onsuccess表示的是连接数据库成功时便会执行该方法,onerror 会是在出现错误的时候执行,还有一个onupgradeneeded方法,该方法只有在第一次初始化数据库时执行,当然当你更新版本号也算是重新初始化一个全新的数据库了。然后就是创建store,创建事务,执行数据添加,查询数据,填充到前端页面控件上,

创建store,这个过程是要在onupgradeneeded方法中操作,只能在这钩子中进行,不然会报Failed to execute ‘createObjectStore’ on ‘IDBDatabase’: The database is not running a version change transaction.

还可能出现的一个错误Failed to exectue ‘transaction’ on ‘IDBDatabase’: One of the specified stores was not found.,这个有可能是你传递的store不对等,根据API,应该在upgradneeded事件的回调函数中调用createObjectStore方法创建store object,不应该在success的回调中

下面贴上部分代码(这里我用了promise,因为这是一个异步操作,你不确定onsuccess是在何时才执行


class UtilDB {
  constructor(store, ...index) {
    this.store = store;
    this.index = index;
  }
  /**
     * 打开创建数据库 返回promise
     * @param {DB名字} name 
     * @param {版本号} version 
     */
  openDB(name, version = 1, keypath) {
    let indexDB =
      window.indexedDB ||
      window.mozIndexedDB ||
      window.webkitIndexedDB ||
      window.msIndexedDB;
    let request = indexDB.open(name, version);
    const pormise = new Promise((resolve, reject) => {
      request.onerror = e => {
        console.log("连接indexDB数据库失败");
        console.error(e.currentTarget.error.message);
        reject(e.currentTarget.error.message);
      };
      request.onsuccess = e => {
        console.log("连接indexDB数据库成功");
        this.db = e.target.result;
        resolve(this.db);
      };
      request.onupgradeneeded = e => {
        let db = e.target.result;
        if (!db.objectStoreNames.contains(this.store)) {
          let store = db.createObjectStore(this.store, {
            keypath: keypath,
            autoIncrement: true
          });
          this.index.forEach(item => {
            if (Object.prototype.toString.call({}) == "[object Object]") {
              store.createIndex(item.name, item.name, item.options);
            } else {
              store.createIndex(item, item, { unique: false });
            }
          });
        }
      };
    });
    return pormise;
  }

另外在前端记录密码那儿为了防止直接查看到密码,使用了加密算法,下面贴上对应代码



    compile(code) {
      var c = String.fromCharCode(code.charCodeAt(0) + code.length);
      for (var i = 1; i < code.length; i++) {
        c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1));
      }
      return escape(c);
    },
    uncompile(code) {
      code = unescape(code);
      var c = String.fromCharCode(code.charCodeAt(0) - code.length);
      for (var i = 1; i < code.length; i++) {
        c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
      }
      return c;
    }

摘录web前端记住用户名密码

PHP Warning: curl_exec() has been disabled for security reasons in /home/ftp/f/free49568/wwwroot/wp-content/themes/Variant/functions.php on line 490 百度已收录
分享