Chrome extension: pass variables from popup html

I am trying to make a very simple extension for chrome, but I am stuck in passing a variable from popup html.

This is the code that I still have:


manifest:

{ "background": { "scripts": [ "background.js" ] }, "browser_action": { "default_icon": "img/test.png", "default_popup": "popup.html", "default_title": "Auto Clicker" }, "description": "Auto click", "manifest_version": 2, "name": "Auto Clicker", "permissions": [ "activeTab" ], "version": "0.0.1" } 

background.js

 chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { switch (request.directive) { case "popup-click-1": // execute the content script chrome.tabs.executeScript(null, { // defaults to the current tab file: "myscript.js", // script to inject into page and run in sandbox allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0. }); sendResponse({}); // sending back empty response to sender break; } } ); 

myscript.js

 function foo(){ document.getElementById('submit-button').click(); } setInterval(function(){ foo()}, 20000) foo(); 

popup.js

  function clickHandler(e) { chrome.extension.sendMessage({directive: "popup-click-1"}, function(response) { this.close(); // close the popup when the background finishes processing request }); } document.addEventListener('DOMContentLoaded', function () { document.getElementById('submit').addEventListener('click', clickHandler); }) 

popup.html

 <html> <head> <title>test</title> <script src="popup.js"></script> </head> <body> test <form> <input id="1" type = "text"> </br> </form> <button id='submit'> etst </button> </body> </html> 

While I run foo (), when you press the submit button, which runs every 20 seconds. What I want to achieve is to add a number in the popup html and then use that number in myscript.js to set the time of the setInterval function.

So here is the scenario:

I open the page, I click the extension button. There is a popup with a form. I put 30,000 and then hit Sumbit. This way foo () will run every 30 seconds.

+5
source share
1 answer

No need for background script.

Add the script to popup.js and pass in the value:

 function clickHandler(e) { chrome.tabs.executeScript({ code: "var timeout=" + document.getElementById('1').value, allFrames: true }, function(result) { chrome.tabs.executeScript({file: "myscript.js", allFrames: true}, function(result) { }); }); } 

myscript.js will use the timeout variable introduced:

 ............. setInterval(foo, timeout); ............. 
+3
source

Source: https://habr.com/ru/post/1235017/


All Articles