Hoppa till huvudinnehållet

Calling JavaScript function in iFrame

Kommentarer

4 kommentarer

  • Officiell kommentar
    Ryan Cooney

    Please avoid using globalThis. It may happen to work, but this is not supported and it will not work in the future.

    postMessage (via the viewer.post-message command) is the preferred/supported way to message between Web and a parent window. This requires the parent window to have JavaScript that listens for the specific message event and routes it to the appropriate function.

  • Berend Veldkamp

    Have you tried using the globalThis variable? For instance, using Evaluate with =globalThis.alert("Hi") works.

    I'm not sure this will work for calling functions within other iframes. At least it won't if they are cross domain, in which case you would need postMessage().

    0
  • Sean McClurkan

    Thanks, Berend and Ryan!

    Is the viewer.post-message command available in the HTML5 viewer?

    So could I execute a JavaScript function in the viewer.post-message command? Or will it just pass a string back to the parent?

     

    0
  • Ryan Cooney

    The viewer.post-message command is not available in the HTML5 viewer.

    We've just added a new Post Message activity to the JavaScript Web APIs activity pack that will enable this.

    The postMessage() mechanism simply raises a "message" event in the parent frame. It doesn't give you (in the child frame) any ability to directly call a function in the parent. It is the responsibility of the parent application to observe the message and then call the desired function. It would look something like this:

    window.addEventListener("message", (e) => {
    // Check the origin of the message to ensure it is trusted
    // This would be the root URL of the server hosting the child frame
    if (e.origin !== "https://my.domain.com"){
    return;
    }

    // Check if this is a message we are interested in
    if (e.data.type === "some-message-type") {
    // Call the desired function on the page
    doSomething(e.data.value)
    // If you need to send a response back to the child frame you can do this //e.ports?.[0]?.postMessage({ foo: "bar" });
    } });

    This assumes your workflow is posting a message object that looks like this:

    {
    "type": "some-message-type",
    "value": "some-value" // This value could be an object
    }
    1

Du måste logga in om du vill lämna en kommentar.