main.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Copyright 2010 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. (function(holder) {
  21. var port = chrome.extension.connect(), extId = "__SingleFile__";
  22. holder.init(document, {
  23. addListener : function(onMessage) {
  24. port.onMessage.addListener(onMessage);
  25. },
  26. postMessage : function(message) {
  27. port.postMessage(message);
  28. }
  29. }, {
  30. addListener : function(onMessage) {
  31. window.addEventListener("message", function(event) {
  32. var data = event.data;
  33. if (data.indexOf(extId + '::') == 0)
  34. onMessage(JSON.parse(data.substr(extId.length + 2)));
  35. }, false);
  36. },
  37. postMessageToFrames : function(frameSelector, messageFn, params) {
  38. var execute = function(id, selector, fnStr, fnParamsStr) {
  39. var i, frameElements = document.querySelectorAll(selector), fn = eval("(" + fnStr + ")");
  40. for (i = 0; i < frameElements.length; i++)
  41. frameElements[i].contentWindow.postMessage(id + "::" + JSON.stringify(fn(i, JSON.parse(fnParamsStr))), "*");
  42. };
  43. location.href = "javascript:(" + execute.toString() + ")('" + extId + "','" + frameSelector + "','" + messageFn.toString() + "','"
  44. + JSON.stringify(params) + "')";
  45. },
  46. postMessageToParent : function(message) {
  47. var msg = extId + "::" + JSON.stringify(message);
  48. location.href = "javascript:parent.postMessage('" + msg + "', '*')";
  49. }
  50. });
  51. })(singlefile);