Run chrome.tabs.executeScript only when the new tab is created and loaded

494 Views Asked by At

I am trying to create a chrome extension to automate the login process.

I am able to login the website using Process_login2 (fill in the username and password and click login button).

However, when I use Process_login (with addon function to open tab and navigate to the webpage), the login function is failed.

Do you have any idea how to run the script only when the new tab is created and loaded?

window.addEventListener('DOMContentLoaded', function () {
  var Process_login = document.querySelector('#menu_btn_login');
  var Process_login2 = document.querySelector('#menu_btn_login2');
  var Process_SendingMsg = document.querySelector('#menu_btn_sendingMsg');

  Process_login.addEventListener('click', function () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      var url_login = 'https://example.com/#login';
      chrome.permissions.request({ origins: [url_login] }, granted => {
        if (granted) {
          chrome.tabs.create({ url: url_login }, tab => {
            chrome.tabs.executeScript(tab.id, { file: 'scripts/login.js' });
          });
        } else {
          alert('You need to grant permission');
        }
      });
    });
  });

  Process_login2.addEventListener('click', function () {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.executeScript(tabs[0].id, { file: 'scripts/login.js' });
    });
  });
permissions": 
        [
        "tabs",
        "tabCapture",
        "activeTab",
        "declarativeContent", 
        "storage"]
0

There are 0 best solutions below