skip to Main Content

In my .tsx file I have this function:

  const openTabImage = (url: string) => {
    const newWindow = window.open();
    if (!newWindow) {
        console.error("Failed to open a new tab.");
        return;
    }
    newWindow.opener = null;
    newWindow.document.body.innerHTML = 'Loading...';  // Placeholder content while loading
    newWindow.document.body.innerHTML = `<img src="${url}" alt="Document Image"/>`;
  };

Which is called when clicking on a button:

<Button
    title="Afficher l’original"
    onClick={() => openTabImage(imageSrcUrl)}
>
    Afficher l’original
</Button>

The function opens an image on a new tab (as expected).

The original tab had loaded and displayed an image and called some APIs to extract and print information from the image.

However, when the new tab is opened, the original tab gets reloaded and I lose the context.

How do I avoid the original tab from being reloaded?

2

Answers


  1. I’m considering the button is inside a form, which maybe can be resulting in some reload due to posting the form. In that case you could try preventDefault.

    your button

    <Button
     title="Afficher l’original"
     onClick={(e) => openTabImage(e ,imageSrcUrl)}
    >
     Afficher l’original
    </Button>
    

    then your js

    const openTabImage = (event: any, url: string) => {
     event.preventDefault();
     const newWindow = window.open();
     if (!newWindow) {
      console.error("Failed to open a new tab.");
      return;
     }
     newWindow.opener = null;
     newWindow.document.body.innerHTML = 'Loading...';  // Placeholder content while loading
     newWindow.document.body.innerHTML = `<img src="${url}" alt="Document Image"/>`;
    };
    
    Login or Signup to reply.
  2. If the <Button /> is inside a form and is the only single button inside that form, it’s type is considered as submit – which by default submits your form and and takes your page to the action url (by default it’s the current url). Try updating the type to button.

    <Button
        type="button"
        title="Afficher l’original"
        onClick={() => openTabImage(imageSrcUrl)}
    >
        Afficher l’original
    </Button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search