How to populate a text field on a webpage with a chrome extension?

I’m trying to create my first chrome extension but I can’t fill a text field on a web from my chrome extension.

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:

manifeste.json

 {
        "name": "Zero",
        "version": "1.0",
        "manifest_version": 3,
        "description": "Auto fill form GRC",
        "icons": { 
            "16": "icon/icon.png",
            "48": "icon/icon.png",
            "128": "icon/icon.png" 
        },
        "action": {
            "default_popup": "index.html",
            "default_icon": "icon/icon.png"
        },
        "options_page": "options.html",
        "content_scripts": [
            {
                "matches" : [
                    "http://*/*",
                    "https://*/*"
                ],
                "js": ["popup.js"]
            }
        ],
        "permissions": [
            "activeTab",
            "storage",
            "scripting",
            "tabs",
            "clipboardWrite",
            "notifications",
            "contextMenus"
        ]
    }

index.html

<!doctype html>
<html>
<head>
    <style>
        body {
            min-width: 120px;
            overflow-x: hidden;
            font-family: Arial, sans-serif;
            font-size: 12px;
        }

        input, textarea {
            width: 140px;
        }

        input#save {
            font-weight: bold;
            width: auto;

        }
    </style>

</head>
<body>
<h1>GRC</h1>
<center>
    <form>
        <div>
            <label><b>Veuillez saisir un code</b></label>
            <input name="inpt" id="inpt" autocomplete="off"/>
            <p>
                <button id="btn">Enter</button>
                <script src="popup.js"></script>
            </p>
        </div>
    </form>
</center>
</body>
</html>

popup.js

    const button = document.getElementById('btn');
    const input = document.getElementById('inpt');
    
    button.onclick = () => {
      functions[input.value]();
    };
    
    functions = {
      1: function () { document.getElementById('a').value = '9: Object'; },
      2: function () { alert(2); },
      3: function () { alert(3); },
      4: function () { alert(4); },
      5: function () { alert(5); },
      6: function () { alert(6); },
    }

I noticed that the functions launch on the window of the “index.html” extension and not on the target web page, here are the images:

the codes works fine and here is the test link: https://codepen.io/Arthur222/pen/eYrVvwK?editors=1010

but they don’t seem to work on a web page with my extension.

1 Like

#1: Why are we forcing the user to load jquery for something that doesn’t use jquery? (Also, where is this jquery JS supposed to exist?)
#2: What is your code supposed to do if the user hasnt put 1 2 3 4 5 or 6 in the input box?
#3: Why do we have index.html as part of the extension? Aren’t you supposed to be manipulating the active tab, not playing around with your own extension’s stuff?

hello @m_hutley and thanks for the question
#1: I deleted jquery.
#2: I need to create a condition if the user has not put 1 2 3 4 5 or 6 in the input box, a message should appear to tell him to type the correct code.
#3: The only method I know of is with index.html.
If you have any other suggestions, I would be very grateful.

Hello @m_hutley,

I have this code there

const button = document.getElementById('btn');
const input = document.getElementById('inpt');

button.onclick = async evt => {

    const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });
    await chrome.scripting.executeScript({
        target: {
            tabId: tab.id
        },
        files: ['popup.js'],

    });
    await chrome.scripting.executeScript({
        target: {
            tabId: tab.id
        },
        func: inPage,
        args: [input.value],
    });
    window.close();
};

function inPage(index) {
    functions[index]();

to create a background.js file that will allow me to inject my functions on the web page but I don’t know how to adapt it if you have an idea please

Where is that code from? Is that in your index.html?

forget the mistakes, do you have any suggestions please?

I cant give you a suggestion if you answer my question about where this random block of code you’ve spouted is currently placed in your code with “forget that”.

I explain to you, a person named
“wOxxOm” from the Chromium Extensions group on gmail gave me this code to create a background.js file that will allow me to inject the functions on a web page from my extension.

WHERE in your code, have you put this. Is it index.html? popup.js? name a file, any file.

1 Like

i did this

manifeste.json

        {
        "name": "Zero",
        "version": "1.0",
        "manifest_version": 3,
        "description": "Auto fill form GRC",
        "icons": {
            "16": "icon/icon.png",
            "48": "icon/icon.png",
            "128": "icon/icon.png"
        },
        "background": {
            "service_worker": "background.js"
        },
        "action": {
            "default_popup": "index.html",
            "default_icon": "icon/icon.png"
        },
        "options_page": "options.html",
        "content_scripts": [{
            "matches": [
                "http://*/*",
                "https://*/*"
            ],
            "js": ["background.js", "popup.js"]
        }],
        "permissions": [
            "activeTab",
            "storage",
            "scripting",
            "tabs",
            "clipboardWrite",
            "notifications",
            "contextMenus"
        ]
    }

index.html

   <!doctype html>
    <html>
    <head>
        <style>
            body {
                min-width: 120px;
                overflow-x: hidden;
                font-family: Arial, sans-serif;
                font-size: 12px;
            }
    
            input, textarea {
                width: 140px;
            }
    
            input#save {
                font-weight: bold;
                width: auto;
    
            }
        </style>
    
    </head>
    <body>
    <h1>GRC</h1>
    <center>
        <form>
            <div>
                <label><b>Veuillez saisir un code</b></label>
                <input name="inpt" id="inpt" autocomplete="off"/>
                <p>
                    <button id="btn">Enter</button>
                    <script src="background.js"></script>
                </p>
            </div>
        </form>
    </center>
    </body>
    </html>

background.js


    const button = document.getElementById('btn');
    const input = document.getElementById('inpt');
    
    button.onclick = async evt => {
    
        const [tab] = await chrome.tabs.query({
            active: true,
            currentWindow: true
        });
        await chrome.scripting.executeScript({
            target: {
                tabId: tab.id
            },
            files: ['popup.js'],
    
        });
        await chrome.scripting.executeScript({
            target: {
                tabId: tab.id
            },
            func: inPage,
            args: [input.value],
        });
        window.close();
    };
    
    function inPage(index) {
        functions[index]();

popup.js

        const button = document.getElementById('btn');
        const input = document.getElementById('inpt');
        
        button.onclick = () => {
          functions[input.value]();
        };
        
        functions = {
          1: function () { document.getElementsByName('q').value = 'test'; },
          2: function () { alert(2); },
          3: function () { alert(3); },
          4: function () { alert(4); },
          5: function () { alert(5); },
          6: function () { alert(6); },
        }

and I’m doing the test on the page www.google.com but it does not work.

Right… so… I tried to understand the tangled mess.

I gave up. Gutted the thing, and wrote it myself.

manifest.json

{
	"name": "Zero",
	"version": "1.0",
	"manifest_version": 3,
	"description": "Auto fill form GRC",
	"icons": {
		"16": "icon/icon.png",
		"48": "icon/icon.png",
		"128": "icon/icon.png"
	},
	"action": {
		"default_popup": "index.html",
		"default_icon": "icon/icon.png"
	},
	"content_scripts": [{
		"matches": [
			"http://*/*",
			"https://*/*"
		],
		"js": ["popup.js"]
	}],
	"permissions": [
		"activeTab",
		"scripting"
	]
}

index.html

<!doctype html>
<html>
    <head>
        <style>
            body {
			min-width: 120px;
			overflow-x: hidden;
			font-family: Arial, sans-serif;
			font-size: 12px;
            }
			
            input, textarea {
			width: 140px;
            }
			
            input#save {
			font-weight: bold;
			width: auto;
			
            }
		</style>
		
	</head>
    <body>
		<h1>GRC</h1>
		<center>
            <div>
                <label><b>Veuillez saisir un code</b></label>
                <input name="inpt" id="inpt" autocomplete="off"/>
                <p>
                    <button id="btn">Enter</button>
				</p>
			</div>
		</center>
	</body>
	<script src="extension.js"></script>
</html>

extension.js (this just exists because Chrome hates inline javascript.)

	document.getElementById("btn").addEventListener("click", function() {
		chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
			chrome.tabs.sendMessage(tabs[0].id, {functionnum: document.getElementById("inpt").value});
		});
	});

popup.js

chrome.runtime.onMessage.addListener(
  function(request, sender) {
	let functions = {
	1: function () { document.getElementsByName('q')[0].value = 'test'; },
	2: function () { alert(2); },
	3: function () { alert(3); },
	4: function () { alert(4); },
	5: function () { alert(5); },
	6: function () { alert(6); },
	}
	functions[request.functionnum]();
});
1 Like

Great, it works very well thank you very much @ m_hutley, can you help me to make the condition if the person does not type the correct codes a message is displayed

Change the popup code to a switch statement on request.functionnum, and make the default case throw your error message.

1 Like

thank you very much, that’s very kind of you

hello @m_hutley
excuse me my ignorance but I want to ask you another stupid last question, the code that I want to insert in the functions and which must fill an intranet web form works once out of 3 and I have to reset the page and the extension several times here is the code if you have a proposal sorry once again for the inconvenience

chrome.runtime.onMessage.addListener(
  function(request, sender) {
	let functions = {

//code : 1
	1: function () { 
var element = document.getElementById('categorisation_1');
var element = document.getElementById('categorisation_2');
var element = document.getElementById('categorisation_3');
var element = document.getElementById('categorisation_4');
var element = document.getElementById('champContactClient');
var element = document.getElementById('champGravite');
var element = document.getElementsByClassName("btn btn-file-upload")[0];
var element = document.getElementById('champCommentaire');
if (element != null && element.value == '') {
const select1 = document.getElementById('categorisation_1');
const select2 = document.getElementById('categorisation_2');
const select3 = document.getElementById('categorisation_3');
const select4 = document.getElementById('categorisation_4');
select1.addEventListener('change', () => {
select2.removeAttribute('disabled');
select3.removeAttribute('disabled');
select4.removeAttribute('disabled');
});
setTimeout(() => {
select1.value = '2: Object';
select1.dispatchEvent(new Event("change"));
}, 1E3);
setTimeout(() => {
select2.value = '1: Object';
select2.dispatchEvent(new Event("change"));
}, 2E3);
setTimeout(() => {
select3.value = '3: Object';
select3.dispatchEvent(new Event("change"));
}, 3E3);
setTimeout(() => {
select4.value = '1: Object';
select4.dispatchEvent(new Event("change"));
}, 4E3);
document.getElementById('champContactClient').value = '2: Object';
document.getElementById('champGravite').value = '2: Object';
document.getElementsByClassName("btn btn-file-upload")[0].click();
document.getElementById('champCommentaire').value += "no ";
}
},

//code : 2
	2: function () { 
var element = document.getElementById('categorisation_1');
var element = document.getElementById('categorisation_2');
var element = document.getElementById('categorisation_3');
var element = document.getElementById('categorisation_4');
var element = document.getElementById('champContactClient');
var element = document.getElementById('champGravite');
var element = document.getElementsByClassName("btn btn-file-upload")[0];
var element = document.getElementById('champCommentaire');
if (element != null && element.value == '') {
const select1 = document.getElementById('categorisation_1');
const select2 = document.getElementById('categorisation_2');
const select3 = document.getElementById('categorisation_3');
const select4 = document.getElementById('categorisation_4');
select1.addEventListener('change', () => {
select2.removeAttribute('disabled');
select3.removeAttribute('disabled');
select4.removeAttribute('disabled');
});
setTimeout(() => {
select1.value = '1: Object';
select1.dispatchEvent(new Event("change"));
}, 1E3);
setTimeout(() => {
select2.value = '1: Object';
select2.dispatchEvent(new Event("change"));
}, 2E3);
setTimeout(() => {
select3.value = '1: Object';
select3.dispatchEvent(new Event("change"));
}, 3E3);
setTimeout(() => {
select4.value = '1: Object';
select4.dispatchEvent(new Event("change"));
}, 4E3);
document.getElementById('champContactClient').value = '3: Object';
document.getElementById('champGravite').value = '1: Object';
document.getElementsByClassName("btn btn-file-upload")[0].click();
document.getElementById('champCommentaire').value += "yes ";
}
},

Hello m_hutley,

the following error message is displayed if you have a solution and thanks in advance.

did you change index.html?

no the content is still the same without any change

<!doctype html>
<html>
    <head>
        <style>
            body {
			min-width: 120px;
			overflow-x: hidden;
			font-family: Arial, sans-serif;
			font-size: 12px;
            }
			
            input, textarea {
			width: 140px;
            }
			
            input#save {
			font-weight: bold;
			width: auto;
			
            }
		</style>
		
	</head>
    <body>
		<h1>GRC</h1>
		<center>
            <div>
                <label><b>Veuillez saisir un code</b></label>
                <input name="inpt" id="inpt" autocomplete="off"/>
                <p>
                    <button id="btn">Enter</button>
				</p>
			</div>
		</center>
	</body>
	<script src="extension.js"></script>
</html>

Why are we changing to background.js again? Why do we need a background worker for a click-button-send-message script? Why are we sending our background worker script to the browser to embed?

no background in my script i didn’t make any changes to your last script but the only concern is at the line level :
`

document.getElementById(“btn”).addEventListener(“click”, function() {

`