简体   繁体   English

有没有办法制作一个 function 可以稍后在谷歌浏览器扩展中访问?

[英]Is there a way to make a function that can be accessed later in a google chrome extension?

I am trying to make an extension that makes a button which then executes a function, however, because the extension executes a javascript file after the page loads.我正在尝试制作一个扩展,该扩展创建一个按钮,然后执行 function,但是,因为扩展在页面加载后执行 javascript 文件。 However, when I create the button I want to run a function.但是,当我创建按钮时,我想运行 function。 Is there a way I can store a function and variables that can be run and access later by the button?有没有办法可以存储 function 和以后可以通过按钮运行和访问的变量?

var effect = [[1,100],[2,32], [5,3]];
var points = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][0];};return adding;})()
var score = (function(){var adding = 0;for(var i = 0; i<effect.length;i++){adding+=effect[i][1];};return adding;})()
var percentage=(score/points*100).toString()+"%";
this.effect = effect;
this.points = points;
this.score = score;
var percentage = points/score;
function list_effect(){
    var effect_string = "";
    for(var i = 0; i<effect.length;i++){
        effect_string += ((points-effect[i][0])/score) - ((points)/score);
    }
    alert(effect_string);
}
if(percentage == 'NaN%'){
//  alert('ERROR');
}else{
  document.getElementsByClassName("agenda")[0].innerHTML = "<button type=\'button\' id=\'get_list\'>Get List</button>"+ document.getElementsByClassName("agenda")[0].innerHTML;
  document.getElementsByClassName("agenda")[0].innerHTML += "<script>" + "this.effect=" + effect.toString() + ";\nthis.points=" + points.toString()+ ";\nthis.score=" + score.toString() +"document.getElementById(\"get_list\").addEventListener(\"onclick\", list_effect());" + "</script>"
}

I have tryied useing this.我试过用这个。 however that does not work但是这不起作用

  1. <script> won't run when added via innerHTML, you should add it using appendChild <script>通过 innerHTML 添加时不会运行,您应该使用appendChild添加它
  2. normally you don't need to add a <script> element at all, just use createElement and attach the listeners directly通常您根本不需要添加<script>元素,只需使用createElement并直接附加侦听器
var button = document.createElement('button');
button.id = 'get_list';
button.onclick = function (e) {
  // use your variables here directly  
};
// clear the previous contents
document.querySelector('.agenda').textContent = '';
// add the button
document.querySelector('.agenda').appendChild(button);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM