How to fill out a textfield within a form on a webpage from a chrome extension?
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';
ayaz15m
Updated on June 04, 2022Comments
-
ayaz15m almost 2 years
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:
$("#body").val("testing123");
document.getElementById('body').value = 'testing123';
but they do not seem to be working.
-
ayaz15m over 9 yearsthank you! that seems to work when the page is first loaded. Do you know how I could do it so the value is loaded in the textfield once the button is clicked?
-
Parag Gangil over 9 years@ayaz15m : Either you can directly add the button to the page through this content script and add
onclick event
to it, OR , you should use (message passing)[developer.chrome.com/extensions/messaging]. In message passing button click onpopup
will send a message to thecontent script
to run the onclick event on the webpage. -
ayaz15m over 9 yearswould the onclick event occur when the extension button is clicked or the button in the popup. I would like it to occur when the button in the popup is clicked. Would it work the same as what you described?
-
ayaz15m over 9 yearsCan give my button and id="btn" and put the contents of myscript.js inside of: $('#btn').click(function(){ //current code }); Would something like that work?