7O07Y7
7O07Y7

Reputation: 559

Fill form via chrome extension popup

I want to load values from fill.js and when the anchor link in extension popup.html is clicked it will autofill form fields on a remote page that has field IDs of #user + #pw. This is what i currently have in my extension but i'm not sure if it's missing something in the manifest file or if back.js is needed.

fill.js

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("[email protected]")
    $("#pw").val("pass123")
}
});

popup.js

$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});

});

popup.html

<!DOCTYPE html>
<html>
<head>
<title>Autofill</title>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<a href="#" id="fill">Fill</a>
</body>
</html>

manifest.json

    {
    "manifest_version": 2,
    "name": "Autofill",
    "description": "",
    "version": "1.0",

    "browser_action": {
      "default_icon": "icon.png",
       "default_title": "Autofill",
       "default_popup": "popup.html"
    },

    "permissions": [
      "tabs",
      "http://*/*",
      "https://*/*"    
    ]
  }

Remote form fields

<input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">

Upvotes: 2

Views: 6503

Answers (1)

Troy Wray
Troy Wray

Reputation: 1018

You can't access the #fill element from your fill.js, which is injected into the page (i.e. a content script). The popup runs in one scope, the content in another and background in another.

Injecting the jquery and fill scripts as you're doing on the browser action is better than loading it in the manifest because it'll only inject when needed and the handler will be ready by the time you click fill in the popup.

Add this to popup.html:

<script src="jquery.js"></script>
<script src="popup.js"></script>

popup.js:

$("#fill").on("click", function(){
    chrome.runtime.sendMessage({
        action: 'fillFields'
    });
});

fill.js:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "fillFields") {
        $("#user").val("[email protected]")
        $("#pw").val("pass123")
    }
});

Lookup run_at to have control over when scripts are injected. You should have no problem as there's a natural delay between browser action click and being able to click fill.

Upvotes: 2

Related Questions