Shula
Shula

Reputation: 306

ifram inside side_panel of Chrome extension can not connect each other via postMessage

I created simple sidePanel chrome extension and put inside iframe with a web app. Inside the web app (React if it metter) i create button that postMessage (window.parent.postMessage) The sidePanel need to get the msg (window.addEventListener('message', handleMessage))

simple but not working. Is it need to work?

Code of the button inside the app that inside the iframe:

 <button
    onClick={() => {
       window.parent.postMessage(
         'Hello',
         'http://localhost:8081',
       );
    }}
  >
    postMessage
  </button>

Code of sidebar:

import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';

const ORIGIN = 'http://localhost:8081';

function Sidebar() {
  const [msg, setMsg] = useState<string>('no msg');
  useEffect(() => {
    setMsg('init msg');
    const handleMessage = (event: MessageEvent) => {
      if (event.origin !== ORIGIN) {
        console.log('Ignored message from origin:', event.origin);
        return;
      }
      console.log('Message received from iframe:', event.data);
      setMsg(event.data);
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, []);

  return (
    <>
      <div>{msg}</div>
      <iframe
        src={ORIGIN}
        style={{ width: '100%', height: '100%', border: 'none' }}
      ></iframe>
    </>
  );
}

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = createRoot(rootElement);
  root.render(<Sidebar />);
} else {
  console.error('root element not found');
}

Code of manifest:

{
  "manifest_version": 3,
  "name": "Chrome Extension",
  "version": "1.0",
  "description": "A Chrome extension built with React and Webpack.",
  "permissions": [
    "activeTab",
    "scripting",
    "storage",
    "windows",
    "sidePanel",
    "tabs",
    "contextMenus"
  ],
  "background": {
    "service_worker": "background.bundle.js"
  },
  "side_panel": {
    "default_path": "sidebar.html"
  },
  "action": {
    "default_title": "Click to open panel",
    "default_icon": {
      "16": "icon16.png",
      "48": "icon48.png",
      "128": "icon128.png"
    }
  }
}

Upvotes: 0

Views: 25

Answers (0)

Related Questions