0

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.

nTuply
  • 1,364
  • 19
  • 42
  • And where is your iframe? – Jan Pfeifer Jan 26 '23 at 09:20
  • @JanPfeifer The iframe is inside the page. This is actually on Hubspot, so I don't have any control on the page or the iframe. I'm trying to automate filling a specific field in the iframe which is loaded on the Hubspot page of my account. I called the iframe `the-frame` in the example above. – nTuply Jan 26 '23 at 09:22
  • Does this answer your question? [Chrome Extension - Get DOM content](https://stackoverflow.com/questions/19758028/chrome-extension-get-dom-content) – Jan Pfeifer Jan 26 '23 at 09:32
  • @JanPfeifer Not really. I think the problem is with the iframe. I read around SO that we need to inject the script into the iframe, but it doesn't seem to work. Surely I'm missing something – nTuply Jan 26 '23 at 09:42
  • You are mixing context of your own popup window and active tab window. Check https://stackoverflow.com/questions/1964225/accessing-current-tab-dom-object-from-popup-html – Jan Pfeifer Jan 26 '23 at 09:44

0 Answers0