Execute web worker from different origin

前端 未结 3 1093
予麋鹿
予麋鹿 2020-12-14 16:15

I am developing a library which I want to host on a CDN. The library is going to be used on many different domains across multiple servers. The library itself contains one s

3条回答
  •  爱一瞬间的悲伤
    2020-12-14 17:02

    For those who find this question:

    YES.

    It is absolutely possible: the trick is leveraging an iframe on the remote domain and communicating with it through postMessage. The remote iframe (hosted on cdn.mydomain.com) will be able to load the webworker (located at cdn.mydomain.com/worker.js) since they both have the same origin. The iframe can then act as a proxy between the postMessage calls. The script.js will however be responsible from filtering the messages so only valid worker messages are handled.

    The downside is that communication speeds (and data transfer speeds) do take a performance hit.

    In short:

    • script.js appends iframe with src="//cdn.mydomain.com/iframe.html"
    • iframe.html on cdn.mydomain.com/iframe.html, executes new Worker("worker.js") and acts as a proxy for message events from window and worker.postMessage (and the other way around).
    • script.js communicates with the worker using iframe.contentWindow.postMessage and the message event from window. (with the proper checks for the correct origin and worker identification for multiple workers)

提交回复
热议问题