window.open blocked due to active file chooser Chome updated

2.6k Views Asked by At

I was trying the following code in react, and I am getting the following error in Chrome (updated) and Opera browsers. Any idea how to fix it ?

return (
<Button
  component="label"
  role={undefined}
  variant="contained"
  tabIndex={-1}
  startIcon={<CloudUploadIcon />}
>
  Upload file
  <VisuallyHiddenInput type="file" onChange={handleFileUpload} />
</Button>

);

const handleFileUpload = (e) => {
if (!e.target.files) {
  return;
}
const file = e.target.files[0];
const filename = file.name;

window.open(
  import.meta.env.VITE_DAEJAVIEWER + `?image="${filename}"`, // a simply url
  "_blank"
);

};

const VisuallyHiddenInput = styled("input")({
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  overflow: "hidden",
  position: "absolute",
  bottom: 0,
  left: 0,
  whiteSpace: "nowrap",
  width: 1,
})

The error: enter image description here

Also note that Firefox is working, but not in Chrome, Opera, Edge

thanks

2

There are 2 best solutions below

0
sovit thapa On

it is due to you are refereing to the current file.you need to convert it into another blob so that that it will refer to another file than the active one.here you can try this.

function base64toBlob(base64Data, contentType) {
  contentType = contentType || "";
  const sliceSize = 1024;
  const byteCharacters = atob(base64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  return new Blob(byteArrays, { type: contentType });
}

const handleTab = (url) => {
  const newTab = window.open(`${url}`, "_blank");
  if (newTab) {
   
    newTab.addEventListener("unload", () => {
      URL.revokeObjectURL(url);
    });
  } else {
    console.log("error", "haha");
  }
};

const handleFiles = (file) => {
  const fr = new FileReader();
  fr.onload = function () {
    console.log(fr.result);
    const blob = base64toBlob(
      fr.result.replace("data:application/pdf;base64,", ""),
      file.type
    );
    const url = URL.createObjectURL(blob);
    handleTab(url);
  };
  fr.readAsDataURL(file);
};

const fielInput = document.querySelector("#file");
fielInput.addEventListener("change", (e) => {
  if (!e.target.files[0]) return;
  handlePDF(e.target.files[0]);
});
0
Sang On

Restart your browser, then it will be fixed.

If you keep your browser opened while updating Chrome from 122 to 123 (March 21, 2023), it likely that you will face this issue.

enter image description here