首页 > 解决方案 > 如何让我的开始和停止按钮使用 javascript 工作?

问题描述

您好,我目前正在创建一个带有开始和停止按钮的 google chrome 扩展程序,该按钮记录已访问的每个 url。我的开始/停止按钮功能算法没有完全工作。目标是单击开始按钮时,我希望它不断地向我的 html 表中添加一行(每次访问 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>


 

标签: javascripturlbuttongoogle-chrome-extensionhtml-table

解决方案


似乎答案可能很长,所以我只回答草稿。

首先将说明单击开始记录后如何记录。仅使用 popup.js 让 js 保持日志记录并不容易。有一个原因,就是页面动作(popup.js)只有在页面窗口被激活时才有效。单击页面操作按钮(扩展插件按钮)时,popup.js 开始激活。当 popup.html 关闭时,js 将停止。当网页转到其他页面时,popup.html 将关闭。要保持记录 content.js 是必需的。

content.js 在特定 url 的当前选项卡上执行。如果 manifest.json 上的 url 匹配条件是 <all_url> ,那么在每个网页上都会执行 js 文件。如果使用日志记录功能,则 content.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

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

on popup.html(开始/停止)-> content.js(日志记录)

我在下面添加的代码仅激活 popup.js 上的日志记录。部分部分进行了编辑。

已编辑

  • manifest.json: 权限 - storage(for chrome.storage), activateTab(for current url), declarativeContent(foractivating popup.html)
  • background.js:激活单击浏览器插件图标时需要声明内容。存储日志显示在后台控制台上。
  • popup.js:storage.local.setLogger(). getBackgroundPage更改为chrome.tabsfor 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>
                                                         


推荐阅读