1
votes

I made an extension with popup window and one button. When this button clicked, extension open all links on the page with class '.link' a new tab. But when I clicked nothing works :( How to link 2 scripts?

popup.js

 document.addEventListener('DOMContentLoaded', function() {
 let openScreensBtn = document.getElementById('btnScreens');
 openScreensBtn.addEventListener('click', function() {
  let links = document.querySelectorAll('.link');
  let arrLinks = Array.from(links);
  let arrHref = [];
  for (let i = 0; i < arrLinks.length; i++) {
    arrHref.push(arrLinks[i].getAttribute('href'));
  };
  for (let i = 0; i < arrHref.length; i++) {
    window.open(arrHref[i], '_blank');
  };
 });
});

popup.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Index</title>
  <script src="popup.js"></script>
</head>

<body>
  <button id="btnScreens">Open Screens</button>
</body>

</html>

manifest.json

{
    "name": "Ext",
    "description" : "",
    "version": "1.0",
    "manifest_version": 2,

    "browser_action": {
        "default_icon": "128.png",
        "default_popup": "popup.html"
    },

    "permissions": [
        "activeTab"
    ]
}
1
The popup is a separate page with its own chrome-extension URL. It's just like a separate tab from another site so it has its own DOM and links. See How to access the webpage DOM rather than the extension page DOM?wOxxOm
@wOxxOm thank you! But I dont understand how to link content script code in my script.js file (for example) chrome.tabs.executeScript({ code: 'document.body.style.backgroundColor="orange"' }); to my pop-up button :(Dmitry Volkov
Make sure you open the correct devtools: right-click the popup and click "inspect". You'll probably see an error about inline code being blocked, which means you need to attach the onclick listener in your js file, not in HTML.wOxxOm

1 Answers

1
votes

Think of this as two isolated parts that could communicate with each other via extension background script. So the thing you would need to do is:

  1. add a self executable script in your popUp.html page that would set up a connection with the extension background script once loaded. extension messaging

  2. on extension background once received a connection from popUp.html inject a contentScript on activeTab

  3. then you would need to set up a connection with the injected content script. You could use the same approach as in step 1 or usetabs connect API from background in the callback of the step 2

  4. Then you could search all the links with .link class and pass that back to the popUp.html using the connection set up.

PS: follow @wOxxOm advice on debugging since all parts are isolated:

  • popUp.html - right click browser action button and click Inspect popUp

  • content_script - page debug console

  • background script - extension debugger