Javascript – How to fill out a textfield within a form on a webpage from a chrome extension

cssgoogle-chromehtmljavascriptjquery

So far I have got an extension that lists out the webpage the user is on and a button. The button should, when clicked, fill in the textfield with "testing123".

On the webpage where I am testing the form has a id and name "form" and the textfield has an id and name "body".

If I could get some help filling in this textfield or a general textfield it would be greatly appreciated.

Here are the files I have so far:

manifest.json


    {
      "name": "Extension Menu",
      "version": "1.0",
      "manifest_version": 2,
      "description": "My extension",
      "browser_action": {
        "default_icon": "icon.png",
        "default_menu": "Menu",
        "default_popup": "popup.html"
      },
      "icons": {
        "128": "icon.png"
      },
      "permissions": [
          "tabs", "http://*/*", "activeTab"
        ]
    }

popup.html

<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<script type="text/javascript" src="popup.js"></script><br>
<button type="button" onclick="fill in text box with the word 'testing123'">Go!</button>

popup.js


    chrome.tabs.getSelected(null, function(tab) {
      // $("#body").val("testing123");
      // document.getElementById('body').value = 'testing123';
      document.getElementById('currentLink').innerHTML = tab.url;
    });

I have tried using:

  1. $("#body").val("testing123");

  2. document.getElementById('body').value = 'testing123';

but they do not seem to be working.

Best Answer

You can't access the webpage directly from popup. You should use content scripts to do this. Content scripts run in the context of the webpage.

Add this to your manifest :

"content_scripts": [
        {
            "matches": [
                "http://www.example.com/*"
            ],
            "js": [
                "jquery.js",
                "myscript.js"
            ]
        },

myscript.js :

$("#body").val("testing123");

document.getElementById('body').value = 'testing123';
Related Topic