简体   繁体   中英

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", "https://ajax.googleapis.com/"],
"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!");
    console.log(window.location.href);
    console.log()
    var pageURL = window.location.href;
    if (pageURL.indexOf('example.com')) {
        console.log('example.com');
        var metaTags = document.querySelectorAll('meta');
        for (var i = 0; i < metaTags.length; i++) {
            console.log(metaTags[i].getAttribute('content'));

            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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM