Unable to use Components in WebExtensions: get “ReferenceError: Cu is not defined”

旧巷老猫 提交于 2020-01-20 08:49:06

问题


I have a simple extension where I use Cu.import to import a JavaScript code module. But, when I load the extension, I get this error:

Cu is not defined

The code I was trying to use was:

Cu.import("resource://gre/modules/MatchPattern.jsm");
Cu.import("resource://gre/modules/BrowserUtils.jsm");

var regExArray = [];
var myArray = ["facebook.com", "google.com"];

var myURL="http://www.google.co.uk/?gfe_rd";

for (var x=0; x<myArray.length; x++)
{   
    console.log("loop: "+x);
    var match = new MatchPattern(/(http:\/\/)(.*\.)*(myArray[x])(\/.*)*(\/)*/);
    log("match result is: "+match.matches(myURL));     
}//end for loop

I know how to define Cu in the Firefox Add-on SDK using require, but how can define it in WebExtesnions?


回答1:


You can NOT use Components in WebExtensions

For the older Firefox extension types, the Components Object provided access to low-level capabilities in Firefox. The common aliases are:

  • Cc = Components.classes
  • Ci = Components.interfaces
  • Cu = Components.util
  • Cr = Components.results
  • Cm = Components.manager
  • components = Components

In the Add-on SDK these were described in the Chrome Authority documentation and were available by using

var {Cc, Ci, Cu, Cr, Cm, components} = require("chrome");

Components does not exist in WebExtensions

Access to these low-level capabilities does not exist in WebExtensions. Remove it from your code and forget about it. Don't try to use anything connected to it, because you can't do so. Removing access to the low-level capabilities provided by Components is one of the specific reasons for moving to WebExtensions.

If you see it in a page on MDN, then that page is not about WebExtensions and should be ignored for WebExtensions development. You should see at the top of every such page a large warning stating that you should be using WebExtensions instead of the technology described on that page. The warning currently (2017-06-17) looks like:

If you need something that exists in older extensions, but not in WebExtensions, try a WebExtensions Experiment

You can extend the capabilities of WebExtensions by constructing a WebExtensions Experiment. The intent is to allow add-on developers to create new APIs for WebExtensions which are proposed for inclusion into Firefox. However, there is no guarantee that such proposals will actually be integrated into Firefox.



来源:https://stackoverflow.com/questions/44608110/unable-to-use-components-in-webextensions-get-referenceerror-cu-is-not-define

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!