Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

javascript - From a browser action popup: open a new tab and fill input fields

I'm trying to build a basic Chrome extension that, from a browser action popup, opens a website in a new tab, and fills in the login credentials. I can get the Chrome extension to open the new page but can't seem to get it to input text into the input fields.

Manifest.json

{
  "manifest_version": 2,

  "name": "Vena",
  "description": "This extension will allow users to login to vena accounts",
  "version": "1.0",

  "browser_action": {
   "default_icon": "images/icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab"
   ]
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Auto-Login</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Login</h1>
    <button id="checkPage">Login!</button>
  </body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
  var checkPageButton = document.getElementById('checkPage');
  checkPageButton.addEventListener('click', function() {

    var newURL = "https://vena.io/";
    chrome.tabs.create({ url: newURL });

    var loginField = document.getElementsByClassName('js-email form-control input-lg');
    var passwordField = document.getElementsByClassName('js-password form-control input-lg');

    loginField.value = 'gsand';
    passwordField.value = '123';


  }, false);
}, false);

How do I fill in the information in the input areas of the new tab?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another time, you may want to use something other than a popup (e.g. just a plain browser action button, or a panel) to test out your functionality. It is easier to debug things other than a popup due to the fact that the popup will disappear under so many conditions. Once you have the basic functionality debugged, you can move it into a popup and deal with the issues specific to using a popup.

Issues

You need to use a content script to interact with web pages:
The primary issue is that you have to use a content script to interact with a web page, such as manipulating the DOM, as you desire to do. Content scripts have to be injected into the web page. This can be done with a content_scripts entry in your manifest.json, or with chrome.tabs.executeScript() from JavaScript that is in the background context (background scripts, event scripts, popups, panels, tabs containing pages from your add-on, etc.). For what you are doing, chrome.tabs.executeScript() is the way to go.

Additional issues:

  1. chrome.tabs.create() is asynchronous. You need to wait for the callback to execute so the tab exists in order to inject a content script. You can not inject scripts into a tab that does not yet exist. Note: You could use other, more complex, methods of determining when to inject the content script, but the callback for chrome.tabs.create() is a good way to do it in this case.
  2. Once you create the new tab, you want to inject a script. This is not the "active tab", so you need to add "https://vena.io/*" to your permissions in your manifest.json.
  3. The elements you desire to interact with are not immediately available on the page when the content script is run. You need to wait until they are available. I just used a setTimeout loop to poll until the elements are available. I chose to poll on 250ms intervals a maximum of 100 times (25 seconds). The elements were there each time after the first delay.
  4. document.getElementsByClassName() returns an HTMLCollection, not a single element.
  5. Popups close when you activate a different tab. Once the popup is closed/destroyed, you can not do any more processing within the code for the popup. In order to get around that:
    1. In your chrome.tabs.create(), include active:false to prevent the new tab from becoming active immediately.
    2. Call chrome.tabs.update() in the callback for chrome.tabs.executeScript() to active the tab once the content script has been injected (i.e. when you are done with all the processing you are going to do in the popup).

Code

Changes were only needed in your manifest.json and popup.js.

manifest.json

{
  "manifest_version": 2,

  "name": "Vena",
  "description": "This extension will allow users to login to vena accounts",
  "version": "1.0",

  "browser_action": {
     "default_icon": "icon.png",
     "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab", //This is not needed as you never interact with the active tab
    "https://vena.io/*"
  ]
}

popup.js

document.addEventListener('DOMContentLoaded', function() {
  var checkPageButton = document.getElementById('checkPage');
  checkPageButton.addEventListener('click', function() {
    var newURL = "https://vena.io/";
    //Must not make the tab active, or the popup will be destroyed preventing any
    //  further processing.
    chrome.tabs.create({ url: newURL,active:false }, function(tab){
        console.log('Attempting to inject script into tab:',tab);
        chrome.tabs.executeScript(tab.id,{code:`
            (function(){
                var count = 100; //Only try 100 times
                function changeLoginWhenExists(){
                    var loginField = document.getElementsByClassName('js-email form-control input-lg')[0];
                    var passwordField = document.getElementsByClassName('js-password form-control input-lg')[0];
                    //loginField and passwordField are each an HTMLCollection
                    if( loginField && passwordField ){
                        loginField.value = 'gsand';
                        passwordField.value = '123';
                    } else {
                        if(count-- > 0 ){
                            //The elements we need don't exist yet, wait a bit to try again.
                            //This could more appropriately be a MutationObserver
                            setTimeout(changeLoginWhenExists,250);
                        }
                    }
                }
                changeLoginWhenExists();
            })();
        `},function(results){
            //Now that we are done with processing, make the tab active. This will
            //  close/destroy the popup.
            chrome.tabs.update(tab.id,{active:true});
        });
    });
  }, false);
}, false);

May need use document.execCommand('insertText', false, text);

Depending on the page, you may need/want to use:

document.execCommand('insertText', false, textValue);

If you do so, you will need to first select/focus the desired element. This would be instead of setting the .value property. Which you use will depend on what you are actually doing and the composition of the page you are altering. For the specific example in the question, setting the element's .value property works. For inserting text, using `document.execCommand('insertText') is more generally applicable.

May need a MutationObserver

In the above code I use a setTimeout() loop to delay until the desired elements exist. While that works in the above case, depending on your use case, it may be more appropriate for you to use a MutationObserver. Largely, which to use will depend on how immediately you need to respond to the desired elements being added and what type of load you are putting on the page by looking for the elements. For more information about watching for DOM changes see: Is there a JavaScript/jQuery DOM change listener?

UI comment

Currently you have a popup that has a single button: "Login". From a user interaction point of view, it would probably be better to just use a plain browser action button. If you are intending to add functionality to your popup, then go ahead and keep the popup. If you are not going to add functionality, it does not make a lot of sense to force your user to click twice (click: open popup, then click: login) when they could have just clicked once.

Use an actual Password Manager

If this is functionality that you desire, rather than just something you are putting together just to learn, you should use an actual Password Manager. The functionality of securely storing passwords and inserting them appropriately in websites is non-trivial. You can easily make mistakes that result in compromising your security. I strongly recommend that you investigate the various ones available and choose one which fits your needs. Basically, all the ones that I have seen would easily provide you with the functionality you have at this time: open a popup; select the site; go to the site and fill in the user name and password. A password manager is a very significant project. It is not a project to be taken on lightly, or for someone who is not experienced in security issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...