首页 > 解决方案 > 如何将内容脚本中的数据显示到弹出窗口?

问题描述

content.js将从 api 获取数据,数据应该显示在 中popup.html,但我似乎无法设置它,document.getElementById('headline')因为它是null. 有办法解决吗?

清单.json

{
  "manifest_version": 2,
  "name": "AAAAA",
  "description": "AAAAA Descriptionnnnnn",
  "version": "1.0",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ],
  "permissions": [
    "*://*/*"
  ]
}

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="headline" class="headline" style="background-color: #ccc; width: 300px;">
    This is a headline
  </div>
</body>
</html>

内容.js

let getData = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
    method: 'get'
  })
  return response.json()
}

getData().then(data => {
  document.getElementById('headline').innerHTML = data
  console.log(data)
})

标签: javascriptgoogle-chrome-extension

解决方案


将数据转换为内容脚本中的对象,然后将其保存到本地存储chrome.storage.local.set(obj)(需要权限:存储)

将数据加载回弹出脚本中

chrome.storage.local.get(null, result => {
    for (const [key, val] of Object.entries(result)) {
        // ...
    }
});

请参阅示例https://developer.chrome.com/docs/extensions/reference/storage/


推荐阅读