如何使用 javascript 让我的开始和停止按钮工作?

How to get my start and stop button to work using javascript?

您好,我目前正在创建一个 google chrome 扩展程序,其中包含一个开始和停止按钮,用于记录每个 url 已访问过的内容。我的开始/停止按钮功能算法没有完全发挥作用。目标是当单击开始按钮时,我希望它不断向我的 html table 添加一行(每次访问 url)- addRow 函数基本上就是这样做的。并且在单击停止按钮后不再添加任何行。

当前代码:

popup.js

//Start and Stop buttons for logging
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");


//attempt to get start/stop logging buttons to work--underwork
function Logger(isLogging) {
    console.log(isLogging)
        
        if (isLogging){
        
        btnStart.style.display= "block";
        btnStop.style.display= "none";
        
        
        
    } else {
        
        btnStart.style.display= "none";
        btnStop.style.display= "block";
    }
}
addRow();

//button to start/stop logging
document.addEventListener("DOMContentLoaded", function () {
    btnStart.addEventListener("click", function() {Logger(true)}); 
    btnStop.addEventListener("click", function() {Logger(false)});
});


//using storage API to save data for last btn pressed--underwork
chrome.storage.local.set({key: Logger()}, function() {
    console.log('value is set to  ' + Logger());
});

chrome.storage.local.get(['key'], function(result) {
    console.log('value currently is ' + result.key);
});
    


//function to append row to HTML table 
function addRow() {
        //perhaps need an for loop for every page visited 
  
    
    const bg = chrome.extension.getBackgroundPage()    
    Object.keys(bg.get).forEach(function (url) {
    
    //get html table
        // Append product to the table
    var table = document.getElementById("tbodyID");
        
            
            var arr = url.split("/");
            var protocoll = arr[0] + "//" + arr[2];
        
            //inputed data --
            browser= "Google Chrome"; 
            protocol = protocoll;
            downloads = "example";
            description = "example";
            time = Date.now();

        
        //put dates in array and replace it and have var as myDate
    // add new row to the table
                  //1 = in the top 
                  //table.rows.length = the end
                  //table.rows.length/2+1 = the center 

            var newRow = table.insertRow(0);
            
            console.log(table.rows.length)
                  
                  // add cells to the row
                  var browserCell = newRow.insertCell(0);
                  var timeCell = newRow.insertCell(1);
                  var urlCell = newRow.insertCell(2);
                  var protocolCell = newRow.insertCell(3);
                  var downloadsCell = newRow.insertCell(4);
                  var descCell = newRow.insertCell(5);
                  
                  // add the data to the cells
                  
                  urlCell.innerHTML = `${url}`; 
                  timeCell.innerHTML = time;
                    browserCell.innerHTML = browser;
                    descCell.innerHTML = description;
                    protocolCell.innerHTML = protocol;
                    downloadsCell.innerHTML = downloads;
                  console.log("works");
     }) 
            }
 

popup.html

<!--Start button of logging-->
    <button class="button button1" id="click-start" >
    <u> Start Logging </u>
    </button>
    
    <!--Stop button of logging-->
    <button class="button button2" id="click-stop">
    <u> Stop Logging </u>
    </button>
    
    <table class="roundedCorners" id = "tableID" border="1">
        <thead>
        <!--Example table header row with the user, url visited, and time they visited the url etc-->
            <tr>
      <!--categories-->
                <th>Browser</th>
                <th>Timestamp</th>
                <th>URL</th>
                <th>Protocol</th> 
                <th>Downloaded File Names</th> 
                <th>Description</th>
      
            </tr>
        </thead>
        <tbody id= "tbodyID">
           
         
            
        </tbody>
     <!--Goal is to append to this table-->
     
    
    </table>


 

看来答案可能很长,所以我只回答了草稿。

先说明点击开始记录后如何记录。只有 popup.js 让 js 保持记录并不容易。这是有原因的,页面操作(popup.js)仅在页面 window 被激活时才有效。单击页面操作按钮(扩展插件按钮)时,popup.js 开始激活。当 popup.html 关闭时,js 停止。当网页转到其他页面时,popup.html 关闭。要继续记录,需要 content.js。

content.js 在某些 url 上的当前选项卡上执行。如果 url 匹配条件是 manifest.json 上的 则在每个网页上执行 js 文件。如果使用日志记录功能,那么 contents.js 应该获得该功能。 addRow() 应该在 contents.js 文件中。但是应该使用开始和停止按钮然后 popup.js 应该使用 runtime.sendMessage() 发送消息。这对人们来说是不同的,对我来说,我从 content.js 向后台发送关于 if 条件标志的消息。此处参考:

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage

因此 contents.js 文件 addRow() 需要由 runtime.onMessage 执行。因此,当 popup.js 向 contents.js 发送带有标志的消息时,contents.js 决定开始或停止记录。如下所示:

popup.html(start/stop) -> content.js(记录)

我在下面添加的代码仅在 popup.js 上激活登录。部分内容已编辑。

已编辑

  • manifest.json: permission - storage(for chrome.storage), activateTab(for current url), declarativeContent(for activating popup.html)
  • background.js: 激活点击浏览器插件图标时需要declarativeContent。在后台控制台上可以看到存储日志。
  • popup.js: storage.local.setLogger() 中。 getBackgroundPage 更改为 chrome.tabs for url(它从扩展程序访问浏览器选项卡)。
  • popup.html: 加载脚本标签popup.js.

//manifest.json
{
    "name": "stackTest",
    "version": "0.0.0.1",
    "permissions": ["storage", "activeTab", "declarativeContent", "https://*/*"],
    "content_scripts": [
      {
        "matches": ["https://*/*"],
        "js": ["contents.js"]
      }
    ],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
      },
      "page_action": {
        "default_popup": "popup.html"
      },
    "description": "this is test.",
    "manifest_version": 2
}



//background.js
chrome.runtime.onInstalled.addListener(() => {

//declarativeContent is needed when popup should be opened
    chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [new chrome.declarativeContent.PageStateMatcher({

            })
        ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
         }])
    });

});

//load key which is logged at popup.js
chrome.storage.local.get(['key'], function(result) {
    console.log('value currently is ' + result.key);
});




//popup.js
//Start and Stop buttons for logging
const btnStart = document.getElementById("click-start");
const btnStop = document.getElementById("click-stop");

//attempt to get start/stop logging buttons to work--underwork
function Logger(isLogging) {
    console.log(isLogging)
        let logger =''
        if (isLogging){
        
        btnStart.style.display= "block";
        btnStop.style.display= "none";
        
        logger = 'logging' 

    } else {
        
        btnStart.style.display= "none";
        btnStop.style.display= "block";

        logger = 'not logging'
    }
                chrome.storage.local.set({key: logger}, function() {
    console.log('value is set to  ' + logger);

})
}
addRow();

//button to start/stop logging
document.addEventListener("DOMContentLoaded", function () {
    btnStart.addEventListener("click", function() {Logger(true)}); 
    btnStop.addEventListener("click", function() {Logger(false)});
});


//using storage API to save data for last btn pressed--underwork
chrome.storage.local.set({key: Logger()}, function() {
    console.log('value is set to  ' + Logger());
});

chrome.storage.local.get(['key'], function(result) {
    console.log('value currently is ' + result.key);
});

//function to append row to HTML table 
function addRow() {
    const bg = chrome.extension.getBackgroundPage()   
        console.log(bg)

        // Used tabs.query for getBackgroundPage 
        // url is got from tabs.query

   // Object.keys(bg.get).forEach(function (url) {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
          let url = tabs[0].url;
    //get html table
        // Append product to the table
           var table = document.getElementById("tbodyID");
            console.log('heelo')

            var arr = url.split("/");
            var protocoll = arr[0] + "//" + arr[2];

            //inputed data --
            browser= "Google Chrome";
            protocol = protocoll;
            downloads = "example";
            description = "example";
            time = Date.now();


        //put dates in array and replace it and have var as myDate
    // add new row to the table
                  //1 = in the top 
                  //table.rows.length = the end
                  //table.rows.length/2+1 = the center 

            var newRow = table.insertRow(0);

            console.log(table.rows.length)

                  // add cells to the row
                  var browserCell = newRow.insertCell(0);
                  var timeCell = newRow.insertCell(1);
                  var urlCell = newRow.insertCell(2);
                  var protocolCell = newRow.insertCell(3);
                  var downloadsCell = newRow.insertCell(4);
                  var descCell = newRow.insertCell(5);

                  // add the data to the cells

                  urlCell.innerHTML = `${url}`;
                  timeCell.innerHTML = time;
                    browserCell.innerHTML = browser;
                    descCell.innerHTML = description;
                    protocolCell.innerHTML = protocol;
                    downloadsCell.innerHTML = downloads;
                  console.log("works");
     })
            }
<!--Start button of logging-->
    <button class="button button1" id="click-start" >
    <u> Start Logging </u>
    </button>

    <!--Stop button of logging-->
    <button class="button button2" id="click-stop">
    <u> Stop Logging </u>
    </button>

    <table class="roundedCorners" id = "tableID" border="1">
        <thead>
        <!--Example table header row with the user, url visited, and time they visited the url etc-->
            <tr>
      <!--categories-->
                <th>Browser</th>
                <th>Timestamp</th>
                <th>URL</th>
                <th>Protocol</th>
                <th>Downloaded File Names</th>
                <th>Description</th>

            </tr>
        </thead>
        <tbody id= "tbodyID">


        </tbody>
     <!--Goal is to append to this table-->


    </table>
    <script src='./popup.js'>
    //To execute popup.js 
    </script>