首页 > 解决方案 > 通过内容脚本将条形图注入网页

问题描述

我将根据页面上呈现的数据将条形图注入到网页中。

为此,我创建了一个 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)

标签: google-chrome-extensionchart.js

解决方案


改成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
                }
            }]
        }
    }
});

推荐阅读