frame_script.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const { interfaces: Ci } = Components;
  6. let workers = {};
  7. let methods = {
  8. /**
  9. * Create a worker with the given `url` in this tab.
  10. */
  11. createWorker: function (url) {
  12. dump("Frame script: creating worker with url '" + url + "'\n");
  13. workers[url] = new content.Worker(url);
  14. return Promise.resolve();
  15. },
  16. /**
  17. * Terminate the worker with the given `url` in this tab.
  18. */
  19. terminateWorker: function (url) {
  20. dump("Frame script: terminating worker with url '" + url + "'\n");
  21. workers[url].terminate();
  22. delete workers[url];
  23. return Promise.resolve();
  24. },
  25. /**
  26. * Post the given `message` to the worker with the given `url` in this tab.
  27. */
  28. postMessageToWorker: function (url, message) {
  29. dump("Frame script: posting message to worker with url '" + url + "'\n");
  30. let worker = workers[url];
  31. worker.postMessage(message);
  32. return new Promise(function (resolve) {
  33. worker.onmessage = function (event) {
  34. worker.onmessage = null;
  35. resolve(event.data);
  36. };
  37. });
  38. },
  39. /**
  40. * Disable the cache for this tab.
  41. */
  42. disableCache: function () {
  43. docShell.defaultLoadFlags = Ci.nsIRequest.LOAD_BYPASS_CACHE
  44. | Ci.nsIRequest.INHIBIT_CACHING;
  45. }
  46. };
  47. addMessageListener("jsonrpc", function (event) {
  48. let { id, method, params } = event.data;
  49. Promise.resolve().then(function () {
  50. return methods[method].apply(undefined, params);
  51. }).then(function (result) {
  52. sendAsyncMessage("jsonrpc", {
  53. id: id,
  54. result: result
  55. });
  56. }).catch(function (error) {
  57. sendAsyncMessage("jsonrpc", {
  58. id: id,
  59. error: error.toString()
  60. });
  61. });
  62. });