google-chrome-extension - 通过内容脚本将条形图注入网页
问题描述
我将根据页面上呈现的数据将条形图注入到网页中。
为此,我创建了一个 Chrome 扩展程序,它使用chartjs来绘制条形图,但是没有用。以下是一个示例,那么如何修复?
可以在这里下载我的扩展。
清单.json
{
"name": "JsonAnalysis2",
"description": "Json Analysis",
"version": "1.0",
"permissions": [
"https://*/*",
"nativeMessaging",
"tabs"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"all_frames": true,
"matches": ["https://*/*"],
"js": ["chart.js","contentScript.js"]
}
],
"page_action": {
"default_title": "",
"default_icon": "icon.png"
},
"manifest_version": 2
}
contentScript.js
// var jq = document.createElement('script');
// jq.src = "https://cdn.jsdelivr.net/npm/chart.js@2.8.0";
// document.querySelector('head').appendChild(jq);
analysisResult=`
<canvas id="myChart"></canvas>
<script type="text/javascript">
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '购买记录',
data: [12, 19, 3, 5, 2, 3],
// backgroundColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor:'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
`
document.body.insertAdjacentHTML('afterBegin',analysisResult)
解决方案
改成manifest.json
以下之后,就成功了!可以在此处下载工作示例。
analysisResult=`
<canvas id="myChart"></canvas>
`
document.body.insertAdjacentHTML('afterBegin',analysisResult)
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '购买记录',
data: [12, 19, 3, 5, 2, 3],
// backgroundColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor:'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
推荐阅读
- linux - 指定 Docker 在 Linux VM 上存储/放置文件的位置
- postgresql - 插入表时如何在 postgresql 中返回列值?
- python-3.x - 为什么情绪分析中的准确度分数为零
- maven - 使用 Jenkins 和 Maven,获取 - 'mvn' 不被识别为内部或外部命令、可运行程序或批处理文件
- c++ - 选择排序(交换指针而不是数据)
- amazon-web-services - 如何在 AWS Cloudformation 中调试“资源创建超时等待完成”?
- python-3.x - 不同子序列 GCD 的数量
- javascript - 正则表达式不起作用。我的代码有什么问题?谁能帮我解决这个问题
- javascript - 如何在数据集上处理 react-leaflet v3 中的事件?
- python - 在python的for循环之外获取gps3数据(在for循环之外调用类函数)