jordsta95
jordsta95

Reputation: 47

Can't get Chrome Extension to run Javascript on webpage

I am trying to make an extension which will run on tumblr.com/dashboard which will hide any div which is "promoted" (i.e. a blog I don't follow, which isn't a paid promotion)

I have the following code in hidestuff.js

$(document).ready(function() {
var hide = $( "div:has(.post_dismiss)" );
for (var i = 0; i < hide.length; i++) {
  var div = hide[i].getAttribute('id');
  var id = "#"+div;
  $(id).hide();
}
});

And the following is what I have in my manifest.json

{
  "manifest_version": 2,
  "name": "I'm Not Following You",
  "version": "0.1",
  "content_scripts": [
    {
      "matches": [
        "https://tumblr.com/dashboard", "http://tumblr.com/dashboard"
      ],
      "js": ["hidestuff.js"]
    }
  ]
}

Tumblr uses jQuery, hence me not including a copy.

I have tested the code (by copying the DOM from my Tumblr dashboard, which included the divs I am trying to hide) and the tests worked. However, adding it to Chrome didn't work.

This is my first attempt at making an extension, and I followed an simple tutorial. It may have been outdated, but there was no date on the tutorial, but I don't know where I am going wrong.

Upvotes: 0

Views: 58

Answers (2)

Haibara Ai
Haibara Ai

Reputation: 10897

  1. Update your matches field in manifest.json, because "https://tumblr.com/dashboard" doesn't match "https://www.tumblr.com/dashboard"

  2. Use your own jquery. Chrome extension doesn't have access to any JavaScript variables or functions created by the page.

So the final version would be:

manifest.json

{
    "manifest_version": 2,
    "name": "I'm Not Following You",
    "version": "0.1",
    "content_scripts": [
        {
            "matches": [
                "https://www.tumblr.com/dashboard",
                "http://www.tumblr.com/dashboard"
            ],
            "js": [
                "jquery.js",
                "hidestuff.js"
            ]
        }
    ]
}

hidestuff.js

$(document).ready(function () {
    var hide = $("div:has(.post_dismiss)");
    for (var i = 0; i < hide.length; i++) {
        var div = hide[i].getAttribute('id');
        var id = "#" + div;
        $(id).hide();
    }
});

Upvotes: 2

Daniel Herr
Daniel Herr

Reputation: 20438

Content scripts do not run in the same context as scripts on the page. You will need to include every library you want to use in your package and in the content scripts manifest section.

https://developer.chrome.com/extensions/content_scripts#execution-environment

Upvotes: 1

Related Questions