首页 > 其他分享 >Chrome扩展开发实例 - 编码解码

Chrome扩展开发实例 - 编码解码

时间:2023-02-17 11:57:45浏览次数:53  
标签:popup const codeStr Chrome 解码 handlers value 实例 type

  • code/manifest.json
{
  "manifest_version": 3,
  "name": "Code Tool",
  "description": "encode and decode string",
  "version": "1.0",
  "action": {
    "default_popup": "popup/popup.html"
  }
}
  • code/popup/popup.html
<html>
  <head>
    <link href="popup.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <h1>Code Tool</h1>
    <select name="codeType" class="codeType" id="codeType">
      <option value="Base64">Base64</option>
      <option value="URIEncode">URIEncode</option>
      <option value="ASCII">ASCII</option>
      <option value="Unicode">Unicode</option>
      <option value="MD5">MD5</option>
    </select>
    <textArea id="codeContent" class="codeContent"> </textArea>
    <div class="btnGroup">
      <input type="button" value="ENCODE" id="enCodeBtn" class="enCodeBtn"/>
      <input type="button" value="DECODE" id="deCodeBtn" class="deCodeBtn"/>
    </div>
    <label for="resultContent" class="resultLabel">Result:</label>
    <textArea id="resultContent" class="resultContent"> </textArea>
    <script src="popup.js"></script>
  </body>
</html>
  • code/popup/popup.css
body {
  padding: 5px 15px;
}
h1 {
  font-size: 14px;
  text-align: center;
}

.codeType {
  margin-bottom: 5px;
}

.btnGroup {
  margin: 10px 15px;
  display: flex;
  justify-content: space-between;
}
.enCodeBtn {
  width: 100px;
  height: 30px;
  background: #d93025;
  color: #FFFFFF;
  cursor: pointer;
}
.deCodeBtn {
  width: 100px;
  height: 30px;
  background: #188038;
  color: #FFFFFF;
  cursor: pointer;
}
.codeContent {
  width: 300px;
  height: 100px;
}

.resultContent {
  width: 300px;
  height: 100px;
}
.resultLabel {
  font-weight: bold;
  font-size: 14px;
}

  • code/popup/popup.js
const codeElement = document.querySelector('#codeContent');
const typeElement = document.querySelector('#codeType');
const resultElement = document.querySelector('#resultContent');

const enCodeBtn = document.querySelector('#enCodeBtn');
const deCodeBtn = document.querySelector('#deCodeBtn');

const handlers = {
  'Base64': {
    encode: codeStr => btoa(codeStr),
    decode: codeStr => atob(codeStr),
  },
  'URIEncode': {
    encode: codeStr => encodeURIComponent(codeStr),
    decode: codeStr => decodeURIComponent(codeStr),
  },

};

enCodeBtn.onclick = () => {
  const codeStr = codeElement.value.trim();
  const type = typeElement.value;
  if(!handlers[type]) return;
  resultElement.value = handlers[type]['encode'](codeStr);
};

deCodeBtn.onclick = () => {
  const codeStr = codeElement.value.trim();
  const type = typeElement.value;
  if(!handlers[type]) return;
  resultElement.value = handlers[type]['decode'](codeStr);
};

标签:popup,const,codeStr,Chrome,解码,handlers,value,实例,type
From: https://www.cnblogs.com/xiaodi-js/p/17129662.html

相关文章