A cross-origin worker is WorkerPool worker created in a JavaScript file on a domain and has been initialized to run JavaScript code on a cross-origin server.
A cross-origin worker is useful because it is a secure solution to the cross-origin restriction policy of the browser. It allows you to make a request to a cross-origin server, even though the browser usually restricts this.
What can it be used for?
- Expose a service to users which was previously unreachable with an XMLHTTPRequest, due to cross-origin restrictions. By using cross-origin workers, you could make a web service API accessible to users' workers by putting a JavaScript worker file on your domain.
- Offline resources that are on another domain. For instance, say you have a photo site and you have a separate server for the pictures. If you wanted to enable Gears offline support, you would have to do a store.capture on them which would fail due to cross-origin restrictions. However, if you had a JavaScript file on the other origin which called store.capture, then you could initiate a worker on that file and it would be successful.
Example
Take a cross-origin resource offline with a cross-origin worker.
----cache_cross_origin_resource.html----
<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript">
// Create the workerpool
var workerPool = google.gears.factory.create('beta.workerpool','1.0');
// Set the message handler for when a worker sends a message
workerPool.onmessage = function(a, b, message) {
alert('Received message from worker ' + message.sender + ': ' + message.text);
};
// Create a worker from a JavaScript file on another origin
var childWorkerId = workerPool.createWorkerFromUrl('http://www.crossorigin.com/worker.js');
// Send a message to the worker. The worker's onmessage handler in worker.js will decide what to do with this
workerPool.sendMessage('crossOriginResource.html', childWorkerId);
</script>
----worker.js----
// Setup the WorkerPool
var wp = google.gears.workerPool;
// Allow a cross-origin script to run this
wp.allowCrossOrigin();
wp.onmessage = function(a,b,messageObject) {
// Ignore messages from unexpected origins
if(messageObject.origin == 'http://www.expectedorigin.com') {
// Create LocalServer
var localServer = google.gears.factory.create('beta.localserver');
// Create ResourceStore (Could also use ManagedResourceStore)
var store = localServer.createStore('Cross_Origin_Store');
// We are capturing the filename sent to us by the
// WorkerPool (crossOriginResource.html)
var fileToCapture = messageObject.text;
// Capture the file
store.capture(fileToCapture, function(url, success, captureId){
// When capture finishes, let the WorkerPool know the status
// This will cause workerPool.onmessage to alert the message received
wp.sendMessage(url + ' captured ' + (success ? 'succeeded' : 'failed'), messageObject.sender);
});
}
}