Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Element targets assume window context #159

Open
HexaCubist opened this issue Oct 31, 2022 · 2 comments
Open

Element targets assume window context #159

HexaCubist opened this issue Oct 31, 2022 · 2 comments

Comments

@HexaCubist
Copy link

The type check here assumes that the target element is in the same window context as the script:

https://github.com/romkor/svelte-portal/blob/master/src/Portal.svelte#L25

This might not always be the case, such as running across iframes or windows. See this StackOverflow answer: https://stackoverflow.com/a/26251098/3902950

Iframes have their own copy of HTMLElement, so target instanceof HTMLElement returns false, while target instanceof otherwindow.HTMLElement returns true.

Open to ideas on how this might be best implemented - perhaps with another optional property specifying the reference window?

  /**
   * Usage: <div use:portal={'css selector'}> or <div use:portal={document.body}> or <div use:portal={document.body} window={otherwindowcontext}>
   *
   * @param {HTMLElement} el
   * @param {HTMLElement|string} target DOM Element or CSS Selector
   * @param {Window} [window=window] Target window DOM document
   */
@HexaCubist HexaCubist changed the title element targets assume window context Element targets assume window context Oct 31, 2022
@HexaCubist
Copy link
Author

Relevant: #142 - the workaround here will solve this issue too, but it might be neater to allow setting the context as a parameter

@HexaCubist
Copy link
Author

HexaCubist commented Nov 3, 2022

Solved this issue for my project with a function found on Stackoverflow:

// Source: https://stackoverflow.com/a/20532809/3902950
const deriveWindow = (elm: HTMLElement | null) => {
    return elm?.ownerDocument?.defaultView || false;
};

The above returns the window context of the given element, which can then be used to:

const tWindow = deriveWindow(target);
if (tWindow && target instanceof tWindow.HTMLElement) {

See implementation here (this version of the library is ported to Typescript): https://github.com/Ranga-Auaha-Ako/canvas-grid-builder/blob/c7b2b75c0b8ecc2413abd1c65bf47f63281b5757/src/lib/portal/portal.svelte

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant