How to load local assets on window.open with CRA

Viewed 91

Using React Portal I created a component that opens a popup window with window.open, loads all of the tags from the original window's head, and renders the children inside that window's body. Let's call it <PopupWindow/>

Code for loading the CSS was taken from: https://gist.github.com/davidgilbertson/ed3c8bb8569bc64b094b87aa88bed5fa#file-copystyles-js

The problem I was having is that fonts and other assets weren't loaded to the new window.

I had 2 non-optimal solutions for the issue:

  1. Put all required assets in the public folder - This is discouraged by CRA as they recommend that assets should be imported in the code.

  2. I created a router in my <App/> component that either routes to the original app or an empty fragment

    export const App: React.FC = () => {
        return (
            <BrowserRouter>
                <Switch>
                    <Route path="/popup">
                        <></>
                    </Route>
                    <Route path="/">
                        <OriginalApp />
                    </Route>
                </Switch>
            </BrowserRouter>
        );
    };
    

    And then in my <PopupWindow/> component I call: window.open(`/popup`, 'popup', windowOptionsStr)

    This doesn't feel right that I have to refactor my whole app to support this popup component.

Note: This is done in an Electron App. So it only runs in Chromium and popups are not blocked.

Is there a better, working and recommended way to load assets to a new window?

0 Answers
Related