partridgejiang / Kekule.js

A Javascript cheminformatics toolkit.
http://partridgejiang.github.io/Kekule.js
MIT License
248 stars 61 forks source link

Webworkers failed when using CDN #298

Open crow02531 opened 1 year ago

crow02531 commented 1 year ago

I load Kekule.js from CDN.

<link rel="stylesheet" href="https://unpkg.com/kekule@1.0.0/dist/themes/default/kekule.css">
<script src="https://unpkg.com/kekule@1.0.0/dist/kekule.min.js"></script>

And I write down these codes in my page:

<script>
  Kekule.OpenBabel.enable(() => {
    chemViewer.setChemObjData('{"format": "smi", "data": "C1CCCCC1"}');
  }
</script>

Then it yields: image

It seems setChemObjData launches a worker new Worker('https://unpkg.com/kekule@1.0.0/dist/extra/kekule.worker.obStructureGenerator.js') and because I use a CDN it undoubtedly fails for Cross-Origin Policy.

I know that this could be fixed simply by installing Kakule.js in my server rather than using a CDN. However, it's a bug, and I hope it could be fixed.

Thanks.

PS: there's a little mistake in tutorial, <script src="https://unpkg.com/browse/kekule@0.9.9/dist/kekule.min.js"></script> won't work, <script src="https://unpkg.com/kekule@0.9.9/dist/kekule.min.js"></script> does.

partridgejiang commented 1 year ago

Hi @crow02531, thanks a lot for your correction to the tutorial. Now it has been fixed and republished.

that worker is used for SMILES to generate atom 2D or 3D coordinates and create correct layout of molecule for displaying in chemViewer. It may be a time-consuming job for large molecules, so an extra web worker is utilized to preventing it from blocking the main thread. To solve the your current issue, you can manually set the path of the worker, forcing it be loaded from localhost:

<script src="https://unpkg.com/kekule@1.0.0/dist/kekule.min.js"></script>
<script>
  Kekule.environment.setEnvVar('openbabel.path', 'http://localhost:4000/YourCustomPathToWorkerAndOpenBabelFiles/');
  Kekule.OpenBabel.enable(() => {
    chemViewer.setChemObjData('{"format": "smi", "data": "C1CCCCC1"}');
  }
</script>

However, such a solution also need to put somes of files of Kekule.js on your own server.

If the corrent layout for SMILES is not important (and the molecule is not needed to be displayed), you may use the IO apis to load it directly:

  Kekule.OpenBabel.enable(() => {
    let molecule = Kekule.IO.loadFormatData('C1CCCCC1', 'smi');
  }

By the way, if molecule data with explicit coordinates (e.g. MOL2k/3k, CML format) is loaded in chem viewer, the web worker will never be loaded.