Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: pass variables from popup html

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

This is the code i have so far:


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>

So far i run foo() when you click the submit button, which runs every 20sec. What i want to achieve is add a number at the popup html and then use that number at myscript.js to set the time of setInterval function.

So here is a case scenario:

I open the page, i hit the extension button. There is a popup with a form. I put 30000 and then hit the sumbit. That way, foo() will run every 30sec.

like image 842

1 Answers

There's no need for the background script.

Inject the script in popup.js and pass 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 injected timeout variable:

.............
setInterval(foo, timeout);
.............
like image 110
wOxxOm Avatar answered Oct 30 '22 05:10

wOxxOm