how to call functions from background.js with a chrome extension

3,169 views
Skip to first unread message

SLAWI MAHDI

unread,
Sep 20, 2022, 6:26:01 AM9/20/22
to Chromium Extensions
I'm creating my first chrome extension and I'm having trouble calling JS functions from the html index page, I think the problem is in the background.js code, here are the components of my extension: 

index.html
-------------------
<!doctype html>
 <html> 
  <head> 
  <style>       
html, body {         height: 80px;         width: 200px;       }    
  </style>
</head> 
  <body> 
  <h1>GRC</h1> 
<form> <div> <label for="example">Veuillez saisir un code</label>
<input name="inpt" id="inpt"/> 
  <button id="btn" onClick="onClickHandler( document.getElementById('inpt').value )">Enter</button>
<script src="background.js"></script> 
</form>
</div>
</body> 
</html> 

background.js
-----------------------
document.addEventListener('DOMContentLoaded', function () { 
  // Get button by ID 
  var button = document.getElementById('btn'); 
  button.onclick = document.getElementById('inpt').value; 
});   
async function onClickHandler(f){ 
 functions[f](); 
 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); 
await chrome.scripting.executeScript({ 
  target: { tabId: tab.id }, 
 files: ['injector.js']   
  });
  window.close(); }

injector.js
----------------
functions = { 
  1 : function(){alert(1);}, 
  2 : function(){alert(2);}, 
  3 : function(){alert(3);},
  4 : function(){alert(4);}, 
  5 : function(){alert(5);}, 
  6 : function(){alert(6);}, 
}  
  function onClickHandler(f){ 
 functions[f]();
  }

thanks for saving me please

wOxxOm

unread,
Sep 20, 2022, 11:18:40 AM9/20/22
to Chromium Extensions, mahd...@gmail.com
  • Right-click the popup, then click "inspect" to open its own devtools and you'll see an error about inline code. You need to remove onClick="......." from your html, it's not supported in extensions.
  • The script "background.js" should be renamed to popup.js both the file and in the html, because the background script is an entirely different thing.
  • There's no need for DOMContentLoaded because the script is already at the end of html
  • button.onclick is incorrectly assigned to a value, but it should be a function (shown below)
  • onClickHandler cannot call `functions` from injector.js because they run in different pages, you'll need to do it in an additional executeScript (shown below)
  • No need for onClickHandler in injector.js 
const button = document.getElementById('btn');
const input = document.getElementById('inpt');

button.onclick = async evt => {

  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['injector.js'],

  });
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: inPage,
    args: [input.value],
  });
  window.close();
};

function inPage(index) {
  functions[index]();

SLAWI MAHDI

unread,
Sep 20, 2022, 11:43:49 AM9/20/22
to Chromium Extensions, wOxxOm

first thank you very much #wOxxOm my goal is to fill fields on a web page with functions that I have already created according to your suggestions now I have

popup.html
-------------------
<!doctype html>
<html>
  <head>
<style>
body {
min-width: 120px;
overflow-x: hidden;
font-family: Arial, sans-serif;
font-size: 12px;
        }
        input, textarea {
            width: 140px;
        }
        input#save {
            font-weight: bold; width: auto;

        }
    </style>

  </head>
  <body>
<h1>GRC</h1>
    <center><form>
  <div>
<label><b>Veuillez saisir un code</b></label>
    <input name="inpt" id="inpt" autocomplete="off"/>
 <p>
<button id="btn">Enter</button>
<script src="popup.js"></script>
</p>
  </div>
</form></center>
  </body>
</html>

popup.js
-----------------------
const button = document.getElementById('btn');
const input = document.getElementById('inpt');

button.onclick = async evt => {

  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['injector.js'],

  });
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: inPage,
    args: [input.value],
  });
  window.close();
};

function inPage(popup) {
  functions[popup]();


injector.js
----------------
functions = { 
  1 : function(){alert(1);}, 
  2 : function(){alert(2);}, 
  3 : function(){alert(3);},
  4 : function(){alert(4);}, 
  5 : function(){alert(5);}, 
  6 : function(){alert(6);}, 
}  


but it still doesn't work sorry for the inconvenience

wOxxOm

unread,
Sep 20, 2022, 11:48:52 AM9/20/22
to Chromium Extensions, mahd...@gmail.com, wOxxOm
Use devtools to investigate why it doesn't work. The popup has its own devtools: right-click the popup, then click "inspect" to open its own devtools.

One of the common problems is the lack of necessary permissions in manifest.json like "scripting" or "activeTab" or "host_permissions", or the active tab is protected against injection e.g. it's a chrome:// tab, chrome-extension:// tab, the start tab page, a chrome web store page, a search page in the Opera browser, or a site blocked via domain policies (you can check ExtensionSettings in chrome://policies).

SLAWI MAHDI

unread,
Sep 21, 2022, 10:29:49 AM9/21/22
to Chromium Extensions, wOxxOm
I have the following error code if you have a proposal?
erreur.png

with the following codes

manifest.json

1.png

2.png

Is there a solution that allows me to do this. I'm fairly new to all of this, so any help would be much appreciated.

SLAWI MAHDI

unread,
Sep 21, 2022, 10:35:21 AM9/21/22
to Chromium Extensions, wOxxOm
tvtools displays the following message:
3.png

SLAWI MAHDI

unread,
Sep 21, 2022, 10:38:20 AM9/21/22
to Chromium Extensions, wOxxOm
I have this error message too
4.png

wOxxOm

unread,
Sep 21, 2022, 12:11:53 PM9/21/22
to Chromium Extensions, mahd...@gmail.com, wOxxOm
The error in chrome://extensions is from the past, you can clear it by clicking the Trash icon or Clear all button. Normally you should always use devtools of the popup.

The error about chrome:// URL is pretty self-explanatory: you can't inject into browser pages. The empty start page when you create a tab is also such a page. There is a special command line switch to allow injection, but you can't use it in an extension that you publish in the web store.

Regarding unexpected property "func" it means you're using an ancient version of Chrome. If you intentionally plan to support such versions, you can use "function:" instead of "func:". For the future, when you see an error about an API method, open the documentation and verify the parameters and the supported versions of Chrome.

SLAWI MAHDI

unread,
Sep 22, 2022, 7:25:52 AM9/22/22
to Chromium Extensions, wOxxOm

please excuse me for the inconvenience, I'm really stuck and my level in English and in javascript is very basic, I noticed that if I modified the content of the injector.js file for example I only put: alert(1); 
it works but when I put all the functions like this:
functions = {
 1 : function(){alert(1);},
 2 : function(){alert(2);},
 3 : function(){alert(3);},
 4 : function(){alert(4);},
 5 : function(){alert(5);},
 6 : function(){alert(6);},
}

 it doesn't work, how can I make the connection between input of the html page and the javascript functions under injector.js? 
I want to write a number that launches the specific function example 1 = 1: function(){alert(1);}, 
excuse me once again for the inconvenience and thank you very much :) wOxxOm

wOxxOm

unread,
Sep 22, 2022, 8:49:43 AM9/22/22
to Chromium Extensions, mahd...@gmail.com, wOxxOm
To declare an array you need [ ] not { }.

SLAWI MAHDI

unread,
Sep 26, 2022, 4:19:01 AM9/26/22
to Chromium Extensions, wOxxOm
I managed to do this which works fine:

manifest.json

  "name": "Zero Retard", 
  "version": "1.0", 
  "manifest_version": 3, 
  "description": "Auto fill form GRC", 
  "action": { 
  "default_popup": "index.html" }
}

popup.js

const button = document.getElementById('btn'); 
const input = document.getElementById('inpt'); 
button.onclick = () => { 
functions[input.value]();
}; 
functions = { 1: function () { alert(1); }, 
  2: function () { alert(2); }, 
  3: function () { alert(3); }, 
  4: function () { alert(4); }, 
  5: function () { alert(5); }, 
  6: function () { alert(6); }, }


but now i want to override the alerts to fill out a form as following: for example, I change "alert(1)" to document.getElementById('categorisation_1').value = '2: Object' ; document.getElementById('categorisation_2').value = '3: Object'; 

and the function will be:

1: function () { document.getElementById('categorisation_1').value = '2: Object'; document.getElementById('categorisation_2').value = '3: Object'; },

Is it possible or not and do you have any suggestions please?

wOxxOm

unread,
Sep 26, 2022, 6:00:56 AM9/26/22
to Chromium Extensions, mahd...@gmail.com, wOxxOm
Looks fine. Go ahead.
Reply all
Reply to author
Forward
0 new messages