简体   繁体   English

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

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

Hello I am currently a create a google chrome extension with a start and stop button that logs every url that has been visited.您好,我目前正在创建一个带有开始和停止按钮的 google chrome 扩展程序,该按钮记录已访问的每个 url。 My start/ stop button function algorithm is not working fully.我的开始/停止按钮功能算法无法正常工作。 The goal is When the start button is clicked I want it to continuously add a row to my html table(every time a url is visited)- which the addRow function basically does.目标是当单击开始按钮时,我希望它不断向我的 html 表中添加一行(每次访问一个 url 时)- addRow 函数基本上就是这样做的。 And to not add any more rows when the stop button has been clicked.并且在单击停止按钮时不再添加任何行。

Current code:当前代码:

popup.js弹出窗口.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弹出窗口.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>


 

Seems it could be long answer so I only answered with draft.似乎答案可能很长,所以我只回答了草稿。

First will explain how to log after clicking start logging.首先说明点击开始记录后如何进行记录。 With only popup.js it will not be easy to let js keep logging.仅使用 popup.js 让 js 保持日志记录并不容易。 There is a reason, which is page action(popup.js) is only alive when page window is activated.有一个原因,即页面操作(popup.js)仅在页面窗口被激活时才处于活动状态。 When clicking page action button(extension plugin button), then popup.js is started to activate.当点击页面动作按钮(扩展插件按钮)时,popup.js 开始激活。 When the popup.html is closed then js is stoped.当 popup.html 关闭时,js 就会停止。 When web page is turned to other page then popup.html is closed.当网页转到其他页面时,popup.html 将关闭。 To keep logging content.js is needed.需要继续记录 content.js。

content.js is executed on current tab on certain url. content.js 在特定 url 的当前选项卡上执行。 If url match condition is <all_url> on manifest.json then on every web page the js file is executed.如果 url 匹配条件是 manifest.json 上的 <all_url> 则在每个网页上执行 js 文件。 If logging function is used then contents.js should get the function.如果使用日志功能,则 contents.js 应该获取该功能。 addRow() should be in contents.js file. addRow()应该在 contents.js 文件中。 But start and stop button should be used then popup.js should send message by using runtime.sendMessage() .但是应该使用开始和停止按钮,然后 popup.js 应该使用runtime.sendMessage()发送消息。 It's different to people, for me I send message to background from content.js as to if condition flag.这对人来说是不同的,对我来说,我从 content.js 向后台发送关于 if 条件标志的消息。 Reference here :参考这里:

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

So on contents.js file addRow() needed to execute by runtime.onMessage .所以在内容addRow()文件addRow()需要由runtime.onMessage执行。 So when popup.js send message to contents.js with a flag then contents.js decides to start or stop logging.因此,当 popup.js 使用标志向 contents.js 发送消息时, contents.js 决定开始或停止记录。 Like below:像下面这样:

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

The codes I added below is only activating logging on popup.js.我在下面添加的代码只是在 popup.js 上激活日志记录。 Some parts are edited.部分部分进行了编辑。

Editted已编辑

  • manifest.json: permission - storage(for chrome.storage ), activateTab(for current url), declarativeContent(for activating popup.html) manifest.json:权限 - 存储(用于chrome.storage )、 activateTab(用于当前 url)、 declarativeContent(用于激活 popup.html)
  • background.js: declarativeContent is needed when activating clicking brower plugin icon. background.js:激活点击浏览器插件图标时需要declarativeContent。 Storage logs are seen on background console.在后台控制台上可以看到存储日志。
  • popup.js: storage.local.set is in Logger() . popup.js: storage.local.setLogger() getBackgroundPage is changed to chrome.tabs for url(it access browser tabs from extension). getBackgroundPage更改为chrome.tabs for url(它从扩展程序访问浏览器选项卡)。
  • popup.html: script tag for loading popup.js. 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>

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

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