PoetryTab 相关API 及代码

2022-01-24 09:34:23 浏览数 (2)

PoetryTab 相关API 及代码

manifest.json

代码语言:javascript复制
{
  "manifest_version": 2,
  "name": "PoetryTab",
  "version": "2.0",
  "description": "PoetryTab:为你的浏览增加诗意",
  "author": "Fizz",
  "icons": {
    "16": "img/logo.png",
    "48": "img/logo.png",
    "128": "img/logo.png"
  },
  "chrome_url_overrides": {
    "newtab": "PoetryTab.html"
  }
}

PoetryTab.html

代码语言:javascript复制
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>你问我最美的诗是什么 我不知道 我只是想起了你</title>
  <link rel="stylesheet" href="css/index.css" />
</head>
<body>
  <div class="container" id="main-container">
    <h1 class="poetry-title" id="poetry-title">独坐敬亭山</h1>
    <div id="poetry-content-wrap">
      <p class="poetry-content">众鸟高飞尽,孤云独去闲。</p>
      <p class="poetry-content">相看两不厌,只有敬亭山。</p>
    </div>
  </div>
  <script src="./js/index.js"></script>
</body>
</html>

index.js

代码语言:javascript复制
// for Poetry Js @Fizz

// 封装一个chrome专用ajax
function ajax(config) {
  let xhr = new XMLHttpRequest()
  xhr.open(config.methods, config.url)
  if (config.methods === 'POST') {
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  }
  if (config.methods === 'GET') {
    xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    // for config.data
  }
  xhr.send()
  xhr.onreadystatechange = function () {
    console.log(xhr.responseText)
    if (xhr.readyState === 4 && xhr.status === 200) {
      config.successCb(xhr.responseText)
    } else {
      // console.log('xhr error', xhr.responseText)
    }
  }
}

// 请求诗数据
function loadPoetry() {
  let sendData = {
    url: 'http://localhost:3000/poetry/getOnePoetry',
    methods: 'GET',
    successCb: function (res) {
      let poetryData = JSON.parse(res).data
      document.querySelector("#poetry-title").innerText = poetryData.title
      let contentHtml = []
      for (let i = 0; i < poetryData.content.length; i  ) {
        let item = poetryData.content[i]
        contentHtml.push(`<p class="poetry-content">${item}</p>`)
      }
      document.querySelector("#poetry-content-wrap").innerHTML = contentHtml.join('')
    }
  }
  ajax(sendData)
}
loadPoetry()

效果图

下载链接

0 人点赞