Detect whether postMessage can send objects?

前端 未结 4 780
灰色年华
灰色年华 2020-12-29 00:30

I\'m looking for a neat way to detect whether postMessage in the browser supports the sending and receiving of objects or just strings. I figure that someone out there must

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 00:57

    You could try to perform an action BEFORE resuming your script. You could try this:

    dummy_task.js

    self.onmessage = function(event) {
        self.postMessage(event.data);
    };
    

    javascript

    workerSupportObject(callback);
    
    function workerSupportObject(callback) {
        var callbackIsCalled = false; // to make sure callback isn't run twice
        var worker = new Worker('dummy_task.js'); // create a worker
    
        // create event
        worker.onmessage = function(event) {
            // if the value is the same as we sent, it probably works
            if(!callbackIsCalled) callback.call(null, event.data.value === 'dummy');
            callbackIsCalled = true;
        };
    
        try {
            // send dummy JSON data
            worker.postMessage({'value': 'dummy'});
        } catch(e) {
            // oh... an error... clearly that's a no.
            if(!callbackIsCalled) callback(null, false);
    
            callbackIsCalled = true;
        }
    }
    
    function callback(objectSupported) {
        console.log('Worker supports objects: ', objectSupported);
    }
    

提交回复
热议问题