Vagif
Vagif

Reputation: 244

javascript in extension not working

I am trying to make a chrome extension that blocks iframes. I have a content.js file that has the javascript code in it but it does not execute. Here is my manifest.json:

{
"manifest_version":2,
"name":"Ad Killer",
"description":"A Basic program for blocking ads",
"version":"0.1",
"background":{
   "scripts":[
     "background.js"
   ]
},
"content_scripts":[
   {
      "matches":[
         "<all_urls>"
      ],
      "js":[
         "jquery.js"
      ]
   }
],
"browser_action":{
   "default_icon":"ad128.png",
   "default_title":"Ad Killer"
 }
}

Cotent.js:

var elems = document.getElementsByTagName("iframe");

for (var i = 0, max = elems.length; i < max; i++) {
    elems[i].hidden = true;

My question is that is there any way to make the javascript in content.js work? Any help would be appreciated.

Upvotes: 1

Views: 46

Answers (1)

SethWhite
SethWhite

Reputation: 1977

Your manifest is currently adding jquery.js to every page you visit. You just need to add content.js to your "content_scripts" array. Assuming content.js is in the same location as your manifest.json:

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

Additionally, you'll want to make sure the code runs when the DOM is ready. Since you're using jQuery:

$(document).ready(function() {
  //your code here
})

There are options for the manifest that define when the scripts run, but I've never had much success with them, you can explore them here: https://developer.chrome.com/extensions/content_scripts see the run_at attribute.

And you may even want to set up a timeout or poll to query for iframes since some of them may be created asynchronously, that is, after the ad content is loaded.

Upvotes: 3

Related Questions