Using local storage in crossrider browser extension code - crossrider

I have to use localStorage variable of browser in extension .js code of crossrider browser extension how to access localStorage variable inside crossrider extenson code
like i want to use localStorae.setItem("foo","demo")
how to access foo varaible in extension code

If I understand you correctly, you can can simply assign the value returned by localStorage to a variable, as follows:
In the extension.js file:
appAPI.ready(function($) {
var dataFromLocalStaorage = localStorage.getItem("foo");
console.log('Value is ' + dataFromLocalStaorage);
});
However, we recommend that you use the following Crossrider APIs to work with local storage: appAPI.db for working synchronously with Crossrider's local database implementation, appAPI.db.async for working asynchronous with Crossrider's local database implementation. This works for all browsers supported by Crossrider.
So, for example, you can save and retrieve data from the local database and use them within your extension code, as follows:
In the extension.js file:
appAPI.ready(function($) {
// Extension variable
var dataToSaveToLocalDB = {scriptName: "Hello World", scriptType: "JS"};
// Save variable to local database
appAPI.db.set('myData', dataToSaveToLocalDB);
// Retrieve variable from the local database
var dataRetrievedFromLocalDB = appAPI.db.get('myData');
// Use the variable in the extension
console.log('Script name: ', dataRetrievedFromLocalDB.scriptName);
});

Related

VS Code: How to access debug variables from within extension?

I am writing an extension for visual studio code where I want to evaluate the current variables of a javascript debug session. These variables are normally shown when one have open the debug pane under the section VARIABLES. See the attached screenshot.
I want to get access to these variables when the user right clicks the editor, but I don't know how.
My current extension setting for this is like that: in the package.json I have registered a menu contribution along with a command:
"contributes": {
"menus": {
"editor/context": [{
"command": "extension.showVariables",
"group": "navigation"
}]
}
}
In my extension.ts I register the command like that:
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.showVariables', () => {
// TODO: let variables = vscode.debug.activeDebugSession.variables.toString();
vscode.window.showInformationMessage(variables);
});
}
I have tried to get them through vscode.debug.activeDebugSession but there is no API for variables here. I also tried to register an event handler for vscode.debug.onDidReceiveDebugSessionCustomEvent but I can't figure out where to search for the debug variables.
Is it even possible to access these variables in an vs extension or do I need to implement my own debugger?
I have managed to get access to the local variables although this is not a general solution - it may only work in a single threaded debugger. If you know any better way, please answer or comment.
Say, the debugger breaks in a method that has a local variable car.
To get the value of car, I am using the customRequest method on the active debug session:
const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('evaluate', { expression: 'car', frameId: frameId });
const car = response.result;
To get the frameId, I use another call of customRequest:
const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('stackTrace', { threadId: 1 })
const frameId = response.stackFrames[0].id;
To get a real car object (not a string representation) in my extension, I pass "JSON.stringify(car)" as expression in the evaluate customRequest. Then, I can use JSON.parse(response.result).
To get all scopes, stacks and variables, have a look at the
Debug Session API and the specification of the DebugProtocol.
You have to talk to the debug adapter using the debug adapter protocol directly using vscode.debug.activeDebugSession.customRequest(command: string, args?: any) (Ref)
This function receives 2 parameters: command and args. Check out this resource to find all possible values of those parameters. One example is the 'evaluate' command that Michael Hilus uses in his answer:
If you want to get the variables in a multi threaded debug session, you must do these requests in this order
Threads Request: Get the thread ids
StackTrace Request: Get the frame ids
Scopes Request: Get the variablesReference
Variables Request: Finally, get the variable names with their values. If a variable is an object you might want to use Variables Request again with the variablesReference of the variable with an object value.
PS: It's kind of hard to find what you want in the DAP specification, so here is a tip:
Go to the 'Types' section in the right menu and find what you want. For instance, Breakpoints.
Ctrl+F and search ': Breakpoint'
Take a look at all matches in the response section of each request.
In the case of variablesReference I had to search variablesReference: number to find it in the responses of Evaluate Request, Scope (type) and Variable (also type).

How do I write a Webpack plugin to generate index.js files on demand?

In general, I want to know how to do code-generation/fabrication in a Webpack plugin on demand. I want to generate contents for files that do not exist when they are "required."
Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).
For example, suppose we have the directory structure:
foo
bar.js
baz.js
main.js
And main.js has:
var foo = require("./foo");
// ...
I want webpack to automatically generate foo/index.js:
module.exports = {
bar: require("./bar"),
baz: require("./baz")
};
I've read most of the webpack docs. github.com/webpack/docs/wiki/How-to-write-a-plugin has an example of generating assets. However, I can't find an example of how to generate an asset on demand. It seems this should be a Resolver, but resolvers seem to only output file paths, not file contents.
Actually for your use case:
Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).
you don't need a plugin. See How to load all files in a subdirectories using webpack without require statements
Doing code-generation/fabrication on demand can be done in JavaScript quite easily, why would you restrict your code generation specifically to only applied, when "required" by WebPack?
As NodeJS itself will look for an index.js, if you require a directory, you can quite easily generate arbitrary exports:
//index.js generating dynamic exports
var time = new Date();
var dynamicExport = {
staticFn : function() {
console.log('Time is:', time);
}
}
//dynamically create a function as a property in dynamicExport
//here you could add some file processing logic that is requiring stuff on demand and export it accordingly
dynamicExport['dyn' + time.getDay()] = function() {
console.log('Take this Java!');
}
module.exports = dynamicExport;

How do you programmatically set MONGO_URL?

How do I set MONGO_URL from within my Meteor app?
I tried
process.env.MONGO_URL = '...'
in my server-side code, outside Meteor.startup, but that isn't working.
I'm using demeteorizer to bundle it into a node.js app. I can't set MONGO_URL in Terminal directly (I'm running my app on a third-party provider).
From Meteorpedia: Environment Variables.
Setting the value of an Environment Variable
The safest time to do this with guaranteed behaviour for any variable
is BEFORE METEOR STARTS. This is usually done either through your
PaaS provider's control panel for your app, or in the shell script
that launches Meteor, e.g.
IMPORTANT: You can also set/change an environment variable from inside Meteor, but you need to set it before it's used. e.g. it's too late to
set MONGO_URL after Meteor has been loaded, but MAIL_URL is ok since
you'll get it set before any mail is sent.
You can overwrite the default collection driver
MongoInternals.defaultRemoteCollectionDriver = _.once(function () {
return new MongoInternals.RemoteCollectionDriver(Meteor.settings.MONGO_URL, {
oplogUrl: Meteor.settings.MONGO_OPLOG_URL
});
});
or set it manually per collection
var database = new MongoInternals.RemoteCollectionDriver(Meteor.settings.MONGO_URL, {
oplogUrl: Meteor.settings.MONGO_OPLOG_URL
});
somecollection = new Mongo.Collection('somecollection', {_driver: database});

How do I read environment variables in Postman tests?

I'm using the packaged app version of Postman to write tests against my Rest API. I'm trying to manage state between consecutive tests. To faciliate this, the Postman object exposed to the Javascript test runtime has methods for setting variables, but none for reading.
postman.setEnvironmentVariable("key", value );
Now, I can read this value in the next call via the {{key}} structure that sucks values in from the current environment. BUT, this doesn't work in the tests; it only works in the request building stuff.
So, is there away to read this stuff from the tests?
According to the docs here you can use
environment["foo"] OR environment.foo
globals["bar"] OR globals.bar
to access them.
ie;
postman.setEnvironmentVariable("foo", "bar");
tests["environment var foo = bar"] = environment.foo === "bar";
postman.setGlobalVariable("foobar", "1");
tests["global var foobar = true"] = globals.foobar == true;
postman.setGlobalVariable("bar", "0");
tests["global var bar = false"] = globals.bar == false;
Postman updated their sandbox and added a pm.* API. Although the older syntax for reading variables in the test scripts still works, according to the docs:
Once a variable has been set, use the pm.variables.get() method or,
alternatively, use the pm.environment.get() or pm.globals.get()
method depending on the appropriate scope to fetch the variable. The
method requires the variable name as a parameter to retrieve the
stored value in a script.

HTML5 File API in Firefox Addon SDK

Is there a way to access Html5 file api in Fire Fox addon sdk in the content script?
This is needed in order to store user added words and their meanings. The data can grow large and so local storage isn't an option.
window.requestFileSystem3 = window.requestFileSystem || window.webkitRequestFileSystem;
gives me the error TypeError: window.requestFileSystem3 is not a function.
I am asking this because i am porting this code from a Google Chrome Extension which allows accessing the file api in a content script.
Additional Questions
1) If HTML5 File API is not allowed then should i use file module?
2) Does the file module allow access to any file on the file system as opposed to the Html5 file api which only access to a sandboxed access to file system?
3) Assuming i have to use file module what would be the best location to store my files ( like the user profile directory or extension directory ) and how would i get this path in code.
I apologize for so many sub questions inside this questions. Google wasn't very helpful regarding this topic.
Any sample code would be very helpful.
Firefox doesn't support writing files via File API yet and even when this will be added it will probably be accessible to web pages only and not extensions. In other words: yes, if you absolutely need to write to files then you should use low-level APIs. You want to store your data in the user profile directory (there is no extension directory, your extension is usually installed as a single packed file). Something like this should work to write a file:
var file = require("sdk/io/file");
var profilePath = require("sdk/system").pathFor("ProfD");
var filePath = file.join(profilePath, "foo.txt");
var writer = file.open(filePath, "w");
writer.writeAsync("foo!", function(error)
{
if (error)
console.log("Error: " + error);
else
console.log("Success!");
});
For reference: sdk/io/file, sdk/system
You could use TextReader.read() or file.read() to read the file. Unfortunately, Add-on SDK doesn't seem to support asynchronous file reading so the read will block the Firefox UI. The only alternative would be importing NetUtil and FileUtils via chrome authority, something like this:
var {components, Cu} = require("chrome");
var {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm", null);
var {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", null);
NetUtil.asyncFetch(new FileUtils.File(filePath), function(stream, result)
{
if (components.isSuccessCode(result))
{
var data = NetUtil.readInputStreamToString(stream, stream.available());
console.log("Success: " + data);
}
else
console.log("Error: " + result);
});