'Simulate clicking elements on the page from a Chrome extension?

I need to iterate and click all the elements with the class .star_gray on page, and keep the iteration and clicking going after redirection. Running JavaScript code cannot meet the second requirement, so I plan to write a Chrome Extension.

But I failed to simulate clicking events on web pages via the extension. My project is as below:

manifest.json

{
  "manifest_version": 2,

  "name": "Check'em All",
  "description": "",
  "version": "1.0",

  "browser_action": {
   "default_popup": "popup.html"
  },
  "background": {
    "persistent": true,
    "scripts": ["jquery.js", "background.js"]
  },
  "content_scripts": [{
    "matches": ["file:///*"],
    "js"     : ["popup.js"]
  }],
  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ]
}

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Check'em All!</title>
</head>
<body>
  <h1>Check'em All!</h1>
  <button id="check-btn">BUTTON</button>
  <script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
  <script src="popup.js"></script>
</body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function () {
  var btn = document.getElementById('check-btn');
  btn.addEventListener('click', injectScript);
});

function injectScript() {
  alert('Handler called!');
  chrome.tabs.executeScript(null, { file: 'background.js' });
}

background.js

$(document).ready(function(){
  $('.star_gray').click();
  $('a.btn.page_next').click();
});

With the code above, when I click the button(#check-btn) on the popup, nothing happens.



Solution 1:[1]

You can't get access DOM in background page. And per your code, you might need to learn more from Official Tutorial, since it seems you are confused with "popup", "background" and "content".

Assuming you want to trigger the click event for all elements with class ".star_gray" in the content page, the following code trigger those events once you click on browserAction.

manifest.json

{
  "name": "Test",
  "version": "1.0",
  "permissions": [
    "tabs"
  ],
  "description": "Test",
  "background": {
    "persistent": false,
    "scripts": [
      "background.js"
    ]
  },
  "content_scripts": [
    {
      "matches": [
        "*://*/*"
      ],
      "js": [
        "jquery.js",
        "content.js"
      ],
      "run_at": "document_end",
      "all_frames": true
    }
  ],
  "browser_action": {
    "title": "Test"
  },
  "manifest_version": 2
}

background.js

chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {command: "click"}, function(response) {
            console.log(response.result);
        });
    });
});

content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)    {
    $('.star_gray').click();
    $('a.btn.page_next').click();

    sendResponse({result: "success"});
});

Solution 2:[2]

Improving the previous answer by @haibara-ai not to use the tabs permission.

Note that in your case you don't even need to watch for ready() since the script runs only when browser action is triggered which is presumably well after DOMContentLoaded.

manifest.json

{
  "name": "Test",
  "version": "1.0",
  "permissions": [
    "activeTab"
  ],
  "description": "Test",
  "background": {
    "scripts": [
      "background.js"
    ]
  },
  "browser_action": {
    "title": "Test"
  },
  "manifest_version": 2
}

background.js

var files = [
    'jquery.js',
    'content.js',
];

chrome.browserAction.onClicked.addListener(function() {
    for (var file of files) {
        chrome.tabs.executeScript({
            file: file,
            allFrames: true,
        });
    }
});

content.js

$('.star_gray').click();
$('a.btn.page_next').click();      

Note, however that this only solves the 'simulate clicking events on web pages via the extension' question. It does not mean that 'keep the iteration and clicking going after redirection' will work. It's best you create another question with the details of what exactly you mean by that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haibara Ai
Solution 2 minj