Some of my features require UniversalXPConnect permissions to be enabled.

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

So, my function looks like this:

function oneOfMyFunctions() {netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); // ...}

In fact, I also tried to catch exceptions when privileges were denied. It looks like this:

try {netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); // ...} catch (e) {// ...}

I would rather treat it as a separate function and call it in my function as follows:

function oneOfMyFunctions() {if (enablePrivilege()) {// ...} else {// ... }}

Given that the enablePrivilege function is as follows:

function enablePrivilege() {try {netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');} catch (e) {return false;} return true;}

However, for security reasons, this is not possible because permissions are only granted within the scope of the requested function.

So, the only option is to include this code block in each of my functions?

renew:

Since I had to try to catch some other exceptions, I ended up with the following design:

function readFile(path, start, length) {netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); var file = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces. nsILocalFile); file.initWithPath(path); var istream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream); istream.init(file, -1, -1, false); istream.QueryInterface(Components.interfaces.nsISeekableStream); istream.seek(0, start); var bstream = Components.classes['@mozilla.org/binaryinputstream;1'].createInstance( Components.interfaces.nsIBinaryInputStream); bstream.setInputStream(istream); return bstream.readBytes(length);}var filepath ='C:\\test.txt', start = 440, length = 5;try {console.log( readFile(filepath, start, length));} catch (e) {if (e.name =='Error') console.log('The privilege to read the file is not granted.'); else console.log('An error happened trying to read the file. ');}

Solution:

You can make enablePrivilege a kind of wrapper function, which accepts a function as a parameter and then calls it inside itself, like this

function enablePrivilege(funcParam) {//enable privileges, in try-catch funcParam();}

So when you call it like this

enablePrivilege(oneOfMyFunctions);

Functions that require privileges should have them because it is called within the scope of enablePrivilege.

javascript-the only option is to include the code block in each of my functions? Related posts

  1. Time Complexity – Big O Notation Course

    Big O notation is an important tools for computer scientists to analyze the cost of an algorithm. Most software engineers should have an understanding of it.We just published a course on the freeCodeCamp.org YouTube channel that will help you understand Big O Notation.Georgio Tunson, aka selikapro, ...

  2. Why is heappop time complexity in python O(logn) (not O(n))?

    For a list, heappop will pop up the previous element. The time complexity of deleting an element from the front of the list is O(n). Am I missing something?Solution:A heappop() rearranges the log(n) elements in the list so that it does not have to move every element.This is easy to see:>>> ...

  3. "Data Structure and Algorithm"-O(3N)=O(N)?

    God's grinding wheel turns very slowly, but it grinds very finely. -MaughamThis article has been included in my GitHub, everyone is welcome to star and issues. https://github.com/midou-tech/articlesBasic concepts of data structuredata structureA collection of data elements that have one or more spec ...

  4. java – Big o notation and recursive function

    I'm trying to learn Big-O notation, but I'm having a hard time calculating the time complexity of a recursive function.Can you help me understand the time complexity of the below example?public int recursiveFunction(int n) { if (n == 0) { return 0; } return Math.max(recursiveFunction(rand(n)) + 2,re ...

  5. Java Get the timestamp at 8 o'clock every day or 8 o'clock the next day

    Get the timestamp at 8 o'clock in the morning of the next day: Date date = new Date(); date.setDate(date.getDate()+1); date.setHours(8); date.setMinutes(0); date.setSeconds( 0); Long goodsTime=date.getTime(); Get the timestamp at eight o’clock every day: Date date = new Date(); dat ...

  6. c#-SingleOrNewIdentified(o => o.prop,value), set o.prop

    I want a C#SingleOrNewIdentified(o => o.prop, value) function that is responsible for returning a new o with o.prop = value preset when Any (o.prop == value) is not found. Unfortunately The thing is, my understanding of expressions and lambdas is very poor.I often find that I need to uniquely set an identifier (e.g. emailAddress, oauthId, GUID, natural key) before using a new EF object in a multiple write mode. The task of writing once often makes me feel uncomfortable. A clear way to tail so ...

  7. java – What is the time complexity of String.toCharArray(), O(n) or O(1)

    Suppose you want to convert a String of length n to a character array of length n.char [] chArray = someString.toCharArray();What is computational complexity? O(n) or O(1) (n: length of someString)My impression is that all it does is allocate memory of size n * sizeof(char) and copy a copy of the st ...

  8. javascript – What do these two lines mean: o [x] = o [x] || {}; o = o [x];{{ a}}

    This is the code I got, but I don't know what these two lines mean:o[arr[i]] = o[arr[i]] || {};o = o[arr[i]];Complete code:var GLOBAL={};GLOBAL.namespace=function(str){ var arr = str.split("."), o=GLOBAL; for(i=(arr[0]=="GLOBAL")? 1: 0 ; i ...

  9. Java I/O Tutorial

    Java I/O TutorialNext &gt Java comes with many handy I/O classes to support the input and output through bytes stream and file system. Here’s a list of the Java I/O examples including file, temporary file and directory manipulation, encoding, serialized and also compression with zip or Gzip.Ha ...

  10. How Big O Notation Works – Explained with Cake

    Big O notation is used in computer science to define an upper bound of an algorithm. It is mostly used to define the maximum time of an algorithm as a function of the input size, but it can also be used to define memory usage.In this article we will talk through the most common types of ‘Big O’ nota ...

  11. Python file I/O Ⅳ

    Directory in Python:All files are contained in different directories, but Python can handle them easily. The os module http://www.xuanhe.net/ has many ways to help you create, delete and change directories.mkdir() methodYou can use the mkdir() method of the os module to create new directories in the current directory. You need to provide a parameter that contains the name of the directory to be created.grammar:example:The following example will create a new directory test in the current director ...

  12. Python file I/OⅡ

    Properties of the File objectAfter a file is opened, you have a file object, and you can get various information about the file.The following is a list of all the attributes related to the file object:Examples are as follows:The output of the above example:close() methodThe close() method of the Fil ...

  13. java I/O system

    18.1 File class18.1.1 Directory Lister18.1.2 Directory utilities18.1.3 Checking and creating the directory18.2 Input and output18.2.1 InputStream Type18.2.2 OutputStream Type18.3 Add attributes and useful interfaces18.3.1 Read data from InputStream via FileterInputStream18.3.2 Write to OutputStream ...

  14. JAVA I/O (6) Multiplexing IO

    In the previous introduction of the Socket and ServerSocket connection interaction process, both reading and writing are blocked. When the socket writes data, the data is first written into the cache of the operating system to form a TCP or UDP load, which is transmitted to the target as a socket. W ...

  15. python - why is this o(n) three-way set disjoint algorithm slower than the o(n^3) version?

    O(n) Since converting a list to a set is O(n) time, getting intersection is O(n) time and len is O(n)def disjoint3c(A, B, C):"""Return True if there is no element common to all three lists."""return len(set(A) & set(B) & set(C)) == 0or similarly, should be explicitly O(N)def set_disjoint_med ...

  16. Big O Notation Explained with Examples

    Big O notation is a way to describe the speed or complexity of a given algorithm. If your current project demands a predefined algorithm, it's important to understand how fast or slow it is compared to other options.What is Big O notation and how does it work?Simply put, Big O notation tells you the ...

Recent Posts

  1. php-wordpress displays the last three posts

    I need to display:first three posts in first div from wordpress,second three posts in second div from wordpress andthird three posts in third div from wordpress.How can I achieve this?div 1 --1st post --2nd tpost --3rd post div 2 --4th post --5th post --6th post div 3 --7th post --8th post --9th postSolution:You can do this in several ways. Put the data into an array, then put it into chunk(), and then iterate over the chunks.Or, you can simply iterate through the data:...

  2. javascript - image onclick instead of button click?

    I have a script that is executed by onclick, but when I use an image it doesn't work, only one button works. You can see an example at http://thomaswd.com/maze. Click the"left"button, then Click the down button and they all work. But for some reason the right arrow doesn't work. Please help. Thanks!...

  3. javascript-Remove fields from the typescript interface object

    I got a json response and stored it in mongodb, but the fields I don't need also entered the database, is there anyway to strip the unethical fields?interface Test{ name:string }; const temp :Test = JSON.parse('{"name":"someName","age":20 }') as Test; console.log(temp);Output:{name:'someName', age: 20}Solution:You can use functions that select certain properties from a given object:function pick(obj: T, ...keys: K[]): Pick { const copy = {} as Pick; keys.forEach(key => copy[key] = obj[key]); ...

  4. java – Jackson-Use loadDataFromNetwork() method to use Robospice to read JSON array

    I am trying to read a JSON array, the format is as follows: [{"vehicle_id":"76","color":"red"}, {"vehicle_id":"7","color":"blue"follows Robospice's Starter Guide.Vehicle.javapublic class Vehicle { @JsonProperty("vehicle_id") private int vehicleID; @JsonProperty("color") private String color; }(The setter and the inhaler follow)The class giving the error: VehiclesRequest.classpublic class VehiclesRequest extends SpringAndroidSpiceRequest{ private static final String METHOD ="systemVehicles"; publ...

  5. java the last day of next month

    I have a date of type variable nowDate and I want to set the variable nextDate to contain the last day of the next month.For example: nowDate = 2013-04-16So nextDate will contain 2013-05-31How can I do this?Solution:tryprivate static Date getNextDate(Date nowDate) { Calendar c = Calendar.getInstance...

  6. Python 2 in Python 3 dict_items.sort()

    I'm porting some code from Python 2 to 3. This is valid code in Python 2 syntax:def print_sorted_dictionary(dictionary): items=dictionary.items() items.sort()In Python 3, dict_items has no method 'sort' - how do I make a workaround for this in Python 3?Solution:Use items = sorted(dictionary.items())...

  7. Python3+TensorFlow to create a smart applet for face recognition

    Chapter 1 Course Guidance This chapter mainly introduces the main content of the course, core knowledge points, application cases involved in the course, general process of deep learning algorithm design, adaptation to the crowd, preconditions for learning this course, and the results achieved after learning And so on, to help everyone understand the overall context of this course as a whole.Chapter 2 Deep Learning Basics (required theoretical knowledge) mainly introduces the basic knowledge of ...

  8. The most popular JavaScript library jQuery

    To learn something, you must first understand its history. For example, when I recently learned JavaScript, whether it is a book or an online resource, it all starts with an introduction to the origin of JavaScript. This part tells us why we should use JavaScript.The origin of JavaScript is basicall...

  9. python-what is the big O symbol of this function

    result = 0 i = 0 while i <2**n: result = result + ii += 1 # end whileI assume O(2^n). Python code.Solution:I think the time complexity of your code is O(2 ^ n log n) because you calculate 2 ^ n for 2 ^ n times. a ^ b can be calculated exponentiation by squaring in O(log b), I think The exponential algorithm in python is an O(log n) algorithm. Therefore, the time complexity is O(2^n log n)....

  10. java-Android screen coordinates to canvas view coordinates

    I'm trying to convert the screen's x and y coordinates to coordinates for drawing on the screen.So I get the screen X and Y coordinates from the MotionEvent triggered by the touch listener.I thought this should be as easy as multiplying it by the matrix used to draw on the canvas, so I created the M...