0

I'm trying to create a button on the extension to click on a link from a certain page, I managed to do some stuff but still can't gain access to the content of the page, here's what i did so far :

background.js

chrome.browserAction.onClicked.addListener(function(tabId, changeInfo, tab){
chrome.tabs.getCurrent(function(tab) {
    if(changeInfo && changeInfo.status == "complete"){
        chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){
            chrome.tabs.executeScript(tabId, {file: "main.js"});
        });
    }
});

manifest.json

 {
  "name": "ext",
  "version": "2.0",
  "manifest_version": 2,
  "description": "ext desc",
  "icons" : {
    "16": "icons/icon16.png",
    "38": "icons/icon38.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "browser_action": 
     {
   "default_icon": "icons/icon16.png",
   "default_popup": "popup.html"
    },
    "background": {
      "matches" :  ["<all_url>"],
      "persistent":true,
      "scripts": [ "background.js"]
  },
  "content_scripts": [
    {
      "matches": ["*://*/*", "file://*/*"],
      "css": ["src/custom.css"],
      "js": ["background.js"]
    }
  ],
  "permissions": [
    "activeTab",
    "tabs"
  ],
  "web_accessible_resources": ["background.js"]

}
  • I bet you didn't intend to put `background.js` into your `content_scripts`. You can just directly insert jquery.js and main.js into content_scripts. – RmbRT Mar 12 '19 at 22:47
  • shouldn't I? sorry still new to this – aqweeb.com Mar 12 '19 at 22:49
  • The background script is something that runs separated from the tabs. If you close your tab, your background script stays alive, and even if you have 2 tabs, there is only 1 background script executing. – RmbRT Mar 12 '19 at 22:51
  • Thanks, fixed that, although still have an issue accessing to the current page content. – aqweeb.com Mar 12 '19 at 22:54

1 Answers1

0

If you just intend to inject main.js and jquery.js into every tab, then you can just change your content_scripts to the following:

{
  "matches": ["<all_urls>"],
  "js": ["jquery.js", "main.js"]
}  

Note that I fixed the "matches" as well: "<all_urls>" already covers all possible urls.

Also, note that "background.js" does not belong into "web_accessible_resources". This is a place for things such as images that are in your WebExtension folder you wish to display in websites.

EDIT: A very similar problem has been solved in this question's answer, you cannot directly access the tab's page from your popup. To do this, you have to either use the messaging API, or inject code (as shown in the answer). I also found that you have another typo in your background matches: I am pretty sure you forgot to add an 's' to <all_url>.

RmbRT
  • 362
  • 1
  • 9