How to click a button on a webpage from Chrome extension by adding a listener to `window`?

I’m writing a simple Chrome extension which will click a button inside an internal website of my company. Specifically, the website contains a button “Show more” which upon click will show more data.

My problem is that when I execute the Javascript needed to click the button in Chrome console everything works. However when I execute it from the content.js script of the extension the button is not clicked.

This is my manifest.json:

 "manifest_version": 2,
 "name": "asd",
 "description": "qwe",
 "version": "0.1",
 "author": "abc",
 "browser_action": {
   "default_icon": "asd.png",
   "default_title": "Have a good day",
   "default_title": "asd"
"permissions": ["activeTab", ""],
"content_scripts": [
      "matches": ["http://*/*"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true

the content.js is like this:

window.addEventListener('load', function(event) {
    console.log("page load!");
    var pageURL = window.location.href;
    if (pageURL.indexOf('')) {
        var metaTags = document.querySelectorAll('meta');
        for (var i = 0; i < metaTags.length; i++) {

            if (metaTags[i].getAttribute('name') === 'application-name' && metaTags[i].getAttribute('content') === 'XYZ') {
                console.log('got match');
                var buttonClass = document.getElementsByClassName('source-viewer-more-code');
                console.log('buttonClass = ' +  JSON.stringify(buttonClass));
                var button = buttonClass[0];
                console.log("button = " + button);

I do see all console.log prints, however JSON.stringify(buttonClass) prints an empty object and console.log("buttonw = " + button); prints undefined.

I’m currently running the extension locally. Is this a Chrome permissions issue or something else?


If you can read meta tags,I guess it is not an issue with permissions, Make sure that Button is in DOM when you are trying to get it by “getElementsByClassName”(One possible reason for button not in DOM is some js in the page might be populating the button to DOM after an ajax request). (When you execute in console, you might be executing after the element is populated in DOM ) if you expect a button and it is not in the dom use something like setTimeout and wait for the button to be populated by other js in the page.

Leave a Reply

Your email address will not be published. Required fields are marked *