Search code examples
javascriptgoogle-chromegoogle-chrome-extensioncontent-script

Chrome extension content-script javascript - run_at document_end not working correctly


As a test, I am creating a chrome extension which hides the "news" section on the right of facebook and the right side ads. Also change the background color to black.

My problem right now is that when you load facebook, the news and white background shows up for a tiny second and then disappears. So seems like setting the run_at to document_end makes my javascript run after the page is already loaded. I have tried document_start and document_idle too with similar results. How can I make it so that the news section doesn't show up at all?

manifest.json:

{
  "manifest_version": 2,

  "name": "FB_Trending_Hide_ChromeExtension",
  "description": "This extension will hide the trending news section of Facebook",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png"
  },
  "content_scripts": [{
    "run_at": "document_end",
    "matches": ["*://*.facebook.com/*"],
    "js": ["content.js"],
    "all_frames": true
  }],
    "permissions": [
    "tabs", "*://*.facebook.com/*", "activeTab"
  ]
} 

content.js:

document.getElementById("pagelet_trending_tags_and_topics").style.display = 'none';
document.getElementById("pagelet_ego_pane").style.display = 'none';
document.body.style.background = 'black';

Solution

  • This looks like a job for a CSS, "css", content_scripts entry, not JavaScript, "js". Using CSS should be easier: you don't need to even consider that the elements might be added to the page dynamically.

    I'd suggest doing something like:

    manifest.json (content_scripts portion only):

      "content_scripts": [{
        "run_at": "document_start",
        "matches": ["*://*.facebook.com/*"],
        "css": ["facebookContent.css"],
        "all_frames": true
      }],
    

    facebookContent.css:

    #pagelet_trending_tags_and_topics {
        display:none !important;
    }
    #pagelet_ego_pane {
        display:none !important;
    }
    body {
        background:black !important;
    }