javascript - 如何将内容脚本中的数据显示到弹出窗口?
问题描述
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)
})
解决方案
将数据转换为内容脚本中的对象,然后将其保存到本地存储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/
推荐阅读
- json.net - [A]Newtonsoft.Json.Linq.JObject 无法转换为 [B]Newtonsoft.Json.Linq.JObject。A 型源自 'Newtonsoft.Json, Version=9.0.0.0
- mobile - Appium:点击复选框时显示元素不可交互错误
- dart - 如何让四个相同的自定义小部件分别更改文本?
- apache-spark - 我使用 SQL 查询得到结果,但使用 spark.Sql 得到错误
- ios - 删除单元格后进行条件检查的 Swift heightForRow
- java - 无法为事务打开 Hibernate Session;嵌套异常是 org.hibernate.exception
- hibernate - 在@Transactional注解方法下获取当前事务
- processing - 在处理中使用光线进行碰撞检测的最佳方法是什么?
- regex - 如何查找所有 *=* 并将其替换为 * = *
- r - 如何调整随机森林代码以进行质量预测