2016-07-06 35 views
2

消息可以包含任何有效的JSON對象(NULL,布爾型,數字,字符串,數組或對象)Chrome擴展內部使用JSON.stiringify將postMessage添加到背景頁面嗎?

鉻擴展規範指示消息的背景和內容腳本之間傳遞可以是Javascript對象,這意味着我們可以在不使用JSON.stringify的情況下傳遞一個Javascript對象。這是否意味着Chrome在發送消息之前內部執行JSON.stringify?如果不是,如果我只是通過沒有JSONification的Javascript對象,會有性能上的提升嗎?

+2

他們可能使用HTML5結構化克隆,它比JSON更高效和靈活([在本答案中提到](http://stackoverflow.com/a/10916838/1114))。這樣做可能會帶來*微小*的性能提升,而不是手動JSON化。 –

+2

考慮到API是在本地代碼中實現的,它可能在V8中本地串行化。請注意,它與'JSON.stringify'序列化不同。 – Xan

回答

4

的消息被自動JSON序列化(字面使用JSON.stringify)在Chrome的JavaScript墊片層與作爲可在source code of messaging.js中可以看出延長交互:

PortImpl.prototype.postMessage = function(msg) { 
    if (!$Object.hasOwnProperty(ports, this.portId_)) 
     throw new Error(kPortClosedError); 

    // JSON.stringify doesn't support a root object which is undefined. 
    if (msg === undefined) 
     msg = null; 
    msg = $JSON.stringify(msg); 
    if (msg === undefined) { 
     // JSON.stringify can fail with unserializable objects. Log an error and 
     // drop the message. 
     // 
     // TODO(kalman/mpcomplete): it would be better to do the same validation 
     // here that we do for runtime.sendMessage (and variants), i.e. throw an 
     // schema validation Error, but just maintain the old behaviour until 
     // there's a good reason not to (http://crbug.com/263077). 
     console.error('Illegal argument to Port.postMessage'); 
     return; 
    } 
    messagingNatives.PostMessage(this.portId_, msg); 
    }; 

同上,用於JSON.parse:

// Called by native code when a message has been sent to the given port. 
    function dispatchOnMessage(msg, portId) { 
    var port = ports[portId]; 
    if (port) { 
     if (msg) 
     msg = $JSON.parse(msg); 
     port.onMessage.dispatch(msg, port); 
    } 
    }; 

NB chrome.runtime.postMessage/sendMessage只是上面顯示的PortImpl的一個包裝。

相關問題