Search code examples
google-chromeiframegoogle-chrome-extensionchrome-extension-manifest-v3

Chrome Extension: iframe injected into page returns null


I've got a Chrome Extension that loads an iframe with some buttons whose functionality I want to control with a script. The iframe is injected and working. When a user clicks the close icon, I want the iframe to close.

Here are the relevant files: content.js

  // Check if the iframe has not been injected already
  if (!document.getElementById('extension-iframe')) {
    const iframe = document.createElement('iframe');
    iframe.id = 'extension-iframe';
    iframe.src = chrome.runtime.getURL('iframe_content.html');

    document.body.appendChild(iframe);
  }
}

extension_bar.js

document.addEventListener('DOMContentLoaded', function () {
  const closeIcon = document.getElementById('close-icon');
  console.log('Close icon element:', closeIcon);

  closeIcon.addEventListener('click', () => {
    console.log('Close icon clicked');
    const iframe = document.getElementById('extension-iframe');
    console.log('Iframe element:', iframe);
    if (iframe) {
      iframe.remove();
      console.log('Iframe removed');
    }
  });
});

iframe_content.html

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="extension_bar.css">
</head>
<body class="extension-body">
    <header class="extension-header">
      <div class="extension-logo">Your Logo</div>
      <div class="extension-icons">
        <img id="setting-icon" src="images/settings-icon.png" alt="Settings">
        <img id="close-icon" src="images/close-icon.png" alt="Close">
      </div>
    </header>
    <p id="extension-message">...</p>
  <script src="extension_bar.js"></script>
</body>
</html>

However, I can't access the iframe using document.getElementById() and when trying to debug, the console returns ifram element:null. All the other elements are working.


Solution

  • The iframe's inner contents is a separate different environment so its inner script (extension_bar.js) runs inside a different document. It can't access the outer document with the iframe element because the documents are cross-origin.

    To remove the iframe you'll need to do it in the parent document in content.js:

    // iframe script: extension_bar.js
    closeIcon.addEventListener('click', () => {
      chrome.tabs.getCurrent(tab => {
        chrome.tabs.sendMessage(tab.id, 'remove-iframe');
      });
    });
    
    // content script
    chrome.runtime.onMessage.addListener(msg => {
      if (msg === 'remove-iframe') {
        const src = chrome.runtime.getURL('iframe_content.html');
        const el = document.querySelector(`iframe[src="${src}"]`);
        el?.remove();
      }
    });