【问题标题】:jQuery in Firefox extension with no conflict in global namespaceFirefox 扩展中的 jQuery,在全局命名空间中没有冲突
【发布时间】:2012-12-04 18:01:38
【问题描述】:

我已经阅读了很多关于这个问题的帖子,并尝试了所有包含 jQuery 的方法。

如果我在 xul 文件中加载 jQuery 并将其存储在一个变量中,它就可以工作。 (如How to use jQuery in Firefox Extension

jQuery.noConflict();
sbsh.safeWalletUtils.$ = function (selector, context) {
    return new jQuery.fn.init(selector, context || doc);
};
sbsh.safeWalletUtils.$.fn = sbsh.safeWalletUtils.$.prototype = jQuery.fn;

但是,我怀疑这里的建议解决方案要好得多: http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087

loadjQuery: function(wnd){
  var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
 .getService(Components.interfaces.mozIJSSubScriptLoader);
  loader.loadSubScript("chrome://clhelper/content/jquery/jquery-1.5.js",wnd);
  var jQuery = wnd.jQuery.noConflict(true);
  loader.loadSubScript("chrome://clhelper/content/jquery/jquery.hoverIntent.js", jQuery);
  return jQuery;
 },

在页面加载事件处理程序中:

var doc = event.originalTarget;
var wnd = doc.defaultView;
// load jQuery and save it as a property of the window
myprivatejQuery = loadjQuery(wnd)

但是我不断收到 wnd.jQuery undefined..(链接中很少有人说这是问题所在)

我该怎么办? 如何使用 jQuery 而不必担心 Firefox 扩展内部的冲突?

【问题讨论】:

  • 我不知道您的问题的答案,但您应该在执行上述任何操作之前检查 $jQuery 变量是否已经命名空间。
  • 是的,但这也可能意味着它是一个旧版本..无论如何,我必须再试验一下..

标签: jquery firefox firefox-addon add-on browser-extension


【解决方案1】:

经过更多调查,感谢 Omri Baumer 的不懈努力..

我们现在明白为什么会出现错误。

正确的做法不是在 xul 文件中作为包含(我怀疑),而是通过调用解包的 js 对象:

// correct function to load jQuery
var loadjQuery = function(wnd){
  var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
   .getService(Components.interfaces.mozIJSSubScriptLoader);
   loader.loadSubScript("chrome://sbshsafewallet/content/jquery-1.8.3.js", wnd);
   var jQuery = XPCNativeWrapper.unwrap(wnd).$;
   jQuery.noConflict(true);
  return jQuery;
};


// field to store the jQuery for the current document window (as there can be multiple tabs)
var jQueryForWindow = null;

// event to call on window load (didn't include the code, left for reader to do)
windowLoad = function (event)
{
    var appcontent = document.getElementById("appcontent"); // browser  
    appcontent.addEventListener("DOMContentLoaded", pageLoadedInit, false);
}

// load jQuery on DOMContentLoaded event
pageLoad = function (event) {
      var doc = event.originalTarget;
      var wnd = doc.defaultView;
      jQueryForWindow = loadjQuery(wnd);
}


//example of function using the jQuery
function usesjQuery()
{
   var $ = jQueryForWindow;
   //do something with jquery here
}

希望这可以帮助所有被卡住的人!

再次感谢 Omri Baumer!

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2013-04-13
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多