utils.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. module.metadata = {
  6. "stability": "experimental"
  7. };
  8. const { Cc, Ci } = require("chrome");
  9. const io = Cc['@mozilla.org/network/io-service;1'].
  10. getService(Ci.nsIIOService);
  11. const SHEET_TYPE = {
  12. "agent": "AGENT_SHEET",
  13. "user": "USER_SHEET",
  14. "author": "AUTHOR_SHEET"
  15. };
  16. function getDOMWindowUtils(window) {
  17. return window.QueryInterface(Ci.nsIInterfaceRequestor).
  18. getInterface(Ci.nsIDOMWindowUtils);
  19. };
  20. /**
  21. * Synchronously loads a style sheet from `uri` and adds it to the list of
  22. * additional style sheets of the document.
  23. * The sheets added takes effect immediately, and only on the document of the
  24. * `window` given.
  25. */
  26. function loadSheet(window, url, type) {
  27. if (!(type && type in SHEET_TYPE))
  28. type = "author";
  29. type = SHEET_TYPE[type];
  30. if (!(url instanceof Ci.nsIURI))
  31. url = io.newURI(url, null, null);
  32. let winUtils = getDOMWindowUtils(window);
  33. try {
  34. winUtils.loadSheet(url, winUtils[type]);
  35. }
  36. catch (e) {};
  37. };
  38. exports.loadSheet = loadSheet;
  39. /**
  40. * Remove the document style sheet at `sheetURI` from the list of additional
  41. * style sheets of the document. The removal takes effect immediately.
  42. */
  43. function removeSheet(window, url, type) {
  44. if (!(type && type in SHEET_TYPE))
  45. type = "author";
  46. type = SHEET_TYPE[type];
  47. if (!(url instanceof Ci.nsIURI))
  48. url = io.newURI(url, null, null);
  49. let winUtils = getDOMWindowUtils(window);
  50. try {
  51. winUtils.removeSheet(url, winUtils[type]);
  52. }
  53. catch (e) {};
  54. };
  55. exports.removeSheet = removeSheet;
  56. /**
  57. * Returns `true` if the `type` given is valid, otherwise `false`.
  58. * The values currently accepted are: "agent", "user" and "author".
  59. */
  60. function isTypeValid(type) {
  61. return type in SHEET_TYPE;
  62. }
  63. exports.isTypeValid = isTypeValid;