0

I'm working on a solid-js application project with an iframe containing a website of my design. I would like to be able to retrieve the url of the current page contained in the iframe. So I created a button that displays a modal window containing the url of the page visited in the iframe. Here is my code:

return (
    <>
    
    <div className=" dark:bg-gray-800  ">
    <iframe
      width="100%"
      height="1300"
      id="myiframe"
      src="https://gkwhelps.herokuapp.com"
    ></iframe>
    </div>
    {/*test button */}
      <button className="fixed bottom-3 left-14 text-blue-500 " onClick={() => setOpen((o) => !o)}>
      <BsArrowLeftCircle size={41} />
      </button>
      <Show when={open()}>
      
      <Modal onClose={() => setOpen(false)} open={open()} title="Invite People">
                <div className="px-4">
                render(
                  document.getElementById("myiframe")
                );
                </div>
              </Modal>
    </Show>

But when I click on this button, it displays a modal window but which contains the sentence: render(document.getElementById("myiframe"));

Which shows that it did not recognize my code used to display the url of the current page contained by the iframe as a. I searched for the way to get the iframe url on this stack overflow question but nothing.

gks
  • 191
  • 1
  • 4
  • 18

1 Answers1

0

You can use a ref to get the iframe since it is just another element on the page:

import { render } from "solid-js/web";

function App() {
  let ref: HTMLIFrameElement | undefined;

  const getUrl = () => {
    if (ref) {
      console.log(ref.contentWindow?.location.href);
    }
  };

  return (
    <div>
      <iframe
        width="100%"
        height="300"
        id="myiframe"
        src="https://solidjs.com"
        ref={ref}
      ></iframe>
      <button type="button" onClick={getUrl}>
        Get Url
      </button>
    </div>
  );
}

render(() => <App />, document.getElementById("app")!);

We used an if statement in our handler because element will be available after onMount hook runs.

You may get SecurityError if the source does not permit embedding.

snnsnn
  • 10,486
  • 4
  • 39
  • 44