After spending countless hours on S.O trying to find an answer, I am posting this question here because I couldn't find anything that works.
I am trying to create a Chrome Extension which has a button in popup.html
and when I click on that button it should simply populate some fields which are contained in an iframe on that page.
Every time I click on the button, I get the following error:
Uncaught TypeError: Cannot read properties of null (reading 'contentWindow')
Here's my code:
populate.js
const populateFields = (field, value) => {
field.focus();
document.getElementById("the-iframe").contentWindow.document.execCommand('insertText', false, value);
field.dispatchEvent(new Event('change', {bubbles: true}));
}
let myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', function() {
populateFields(document.getElementById("the-iframe").contentWindow.document.querySelector('[data-test-id="custom_field"]'), "My Custom Value");
});
manifest.json
{
"name": "Name",
"version": "0.1",
"manifest_version": 3,
"action": {
"default_popup": "popup.html",
"default_icon": "logo.png"
},
"icons": {
"128": "logo.png"
},
"permissions": ["activeTab"],
"content_scripts": [{
"js": ["populate.js"],
"matches": ["http://*/*", "https://*/*"],
"all_frames": true
}]
}
popup.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1">
<title>My Extension</title>
</head>
<body>
<button id="my-btn">My Button</button>
<script src="populate.js"></script>
</body>
</html>
How can I solve this?
Note: I have no control over the iframe, so I cannot modify it. It seems like it's a same origin on the page though.