I am writing a simple extension to open browser by clicking the extension button. I would like to know if there is a function which can execute passed shell command as argument. Also, it'd be really helpful if anyone can suggest a good simple reference for extension development.
From https://github.com/GNOME/gnome-shell/blob/master/js/misc/util.js:
// Runs #command_line in the background, handling any errors that
// occur when trying to parse or start the program.
function spawnCommandLine(command_line) {
try {
let [success, argv] = GLib.shell_parse_argv(command_line);
trySpawn(argv);
} catch (err) {
_handleSpawnError(command_line, err);
}
}
There are a few variations on that method in there. Save yourself mountains of headaches and just bookmark the GitHub repository.
Some quick links:
popupMenu.js: working with popup menus
panel.js: a good read for implementing "tray" icons
modalDialog.js: some UI elements were made to be reused, runDialog.js uses this for example
mpris.js: there are also good examples of using frameworks like DBus in gjs
I can't stress enough how much you'll get out of reading the gnome-shell source. Unfortunately, it's compiled into a resource file now so we don't have local copies to stumble upon.
UPDATE (2021)
If you're reading this, please instead see the documentation available on gjs.guide. Specifically the documentation on Spawning Subprocesses, which covers why this is a bad idea in extensions and how to do it slightly less bad.
If you're not interested in the result - i.e. when you want to open a browser window - you can just use GLib.spawn_command_line_async like so:
const GLib = imports.gi.GLib;
...
(this._menuEntries[i]).connect('activate', () => {
GLib.spawn_command_line_async('firefox http://example.com?p='+ my_params[i]);
});
If you need a synchronous result, read https://gjs.guide/guides/gio/subprocesses.html
Related
I know that I can type into Chrome or FF the following command:
Object.keys(window);
but this displays DHTMLX stuff and also function names in which I'm not interested in. And it doesn't display variables in functions that have not been executed yet. We have more than 20,000 lines of JavaScript codebase, so I would prefer static code analyis. I found JavsScript Lint. It is a great tool but I don't know how to use it for displaying global vars.
So I'm searching for memory leaks, forgotten var keywords, and so on...
To do [only] what you're asking, I think you're looking for this:
for each (obj in window) {
if (window.hasOwnProperty(obj)) {
console.log(obj);
}
}
I haven't linted that code, which is unlike me, but you get the idea. Try setting something first (var spam = "spam";) and you'll see it reported on your console, and not the cruft you asked about avoiding.
That said, JLRishe is right; JSLint executes JavaScript in your browser without "phoning home", so feel free to run it. There are also many offline tools for JSLinting your code. I use a plugin for Sublime Text, for instance.
If you'd like some simplest-case html/JavaScript code to "wrap" JSLint, I've got an example here. Just download the latest jslint.js file from Crockford's repository into the same directory, and poof, you're linting with a local copy of JSLint.js. Edit: Added code in a new answer here.
Though understand that you're linting locally with that wrapper or when you visit JSLint.com. Honestly, I can say with some confidence, Crockford would rather not see our code. ;^) You download JSLint.js (actually webjslint, a minified compilation of a few files) from JSLint.com, but you execute in the browser.
(Admittedly, you're technically right -- you never know when that site could be compromised, and to be completely on the up and up, you sh/c/ould vet jslint.js each time you grab a fresh copy. It is safer to run locally, but as of this writing, you appear safe to use JSLint.com. Just eyeball your favorite browser's Net tab while running some test, non-proprietary code, and see if any phoning happens. Or unplug your box's network cable!)
Rick's answer to use "use strict"; is another great suggestion.
A great way to catch undeclared variables is to add 'use strict' to your code.
The errors will appear in the console, or you could display them in a try ... catch block:
'use strict';
try {
var i= 15;
u= 25;
} catch(ee) {
alert(ee.message);
}
I found a very good solution to list all the global variables with the jsl command line tool:
Here is the documentation
I just have to put /*jsl:option explicit*/ into each file that I want to check. Then it is enough to run ./jsl -process <someFile> | grep 'undeclared identifier'
It is also possible to use referenceFile that contains some intentional global variables /*jsl:import <referenceFile>*/ so these variables will not be listed.
My team has had the occasional problem of developers pushing Karma/Protractor tests containing the .only() function call, which of course makes our Jenkins etc only run that particular test, potentially allowing bugs to slip by. As such I thought I'd try and figure out a way to stop this from happening without being discovered.
First, I thought I'd look into simply using JSHint to point out the function call, but I can't seem to find a way to do that. I also looked at ESLint for its custom plugins, but I can't figure out how to write a plugin for this particular case.
Could you guys give me some ideas on how to solve this issue? Alternative solutions are also appreciated, of course!
Here's a (probably not working example) of how to create a plugin that flags an error if the parser ever sees a only() call. Again, mileage may vary, but it should be enough to get you started. This does not work if it sees a.only(), we'll leave that up to you.
module.exports.rules = {
"no-only-call": context => ({
CallExpression: (node) => {
if(node.callee.name == "only"){
context.report(node, 'Calls to only() are disallowed');
}
}
})
};
https://www.kenneth-truyers.net/2016/05/27/writing-custom-eslint-rules/ - Simple example of creating a custom rule
http://esprima.org/demo/parse.html - Use this online parser to help you understand the parse tree.
https://www.npmjs.com/package/generator-eslint - Use this generator to start your plugin project
this questions pops up again and again across the internet (even on SO), but I haven't found a satisfying solution to this problem:
How can we change/replace Javascript code in a running web application, without reloading the page?
Many people answer this with "you cannot, because it is impossible". Some experiments with IntelliJ IDEAs live edit plugin proves me that it is possible. But I don't want to be bound to an IDE for this feature. (Bonus: browser independent)
Here is what I tried:
add //# sourceURL=whatever.js to my dynamically loaded script
add folder to Chrome containing whatever.js
mapping the local whatever.js to the network whatever.js
changing code in either does not affect the web-page at all. In fact editing the network-side file results in a oddish "flashing" of the dev tools.
Please understand that I do not expect the changed JS to magically apply to the webpage once I change it, but I expect it to use the new code when the execution point is passed again.
Example:
Given a button that triggers 'alert(1);'
Change to 'alert(2);'
I expect the button to trigger 'alert(2);'
Having many dependencies and a huge script that is triggered pretty late in a workflow it is really a big problem for me to refresh the page, so I need to find a solution that works on-the-fly.
First of all: What you ask for is really tricky and you can find security problems if you allow this in your applications, anyway it is not impossible.
BUT if you want to achieve your example follow this steps:
Make a code snippet like this:
var message = "1"; // this must be a global variable!!!!
function showMessage() {
alert(message);
}
Given a button that triggers 'alert(1);'
Make button call a function ie: onclick='showMessage()'
Change to 'alert(2);'
I expect the button to trigger 'alert(2);'
Now it's easy, When you detect the event that implies to change the alert message to 2 you just need to change message value:
message = "2";
That's all.
Option 1: Livereload
I would say as long it's for develop reasons you can use livereload on your server.
Depends of your server type. I'm note big expert in apach, glassfish and other java's world stuff, but in world of JS (nodejs) this is a shorter way.
(link for npm-livereload)
Hack: You can handle static-files such as js, css with simple node.js server with built-in livereload.
Option 2: jRebel
I'm not sure about js but perhaps JRebel can handle this issue. Anyway it's a good addition to the develop process - at least it would make a java's "hot reload: for you.
Option 3: Monkey-patching
You can use monkey-patching techniques: Each function in js it's just a string, you can turn string -> function with new Function().
just like:
var foo = {
sum: function (a, b) {return a+b;}
}
//...
obj.sum = new Function(....) //Now you're replaced the original code
check this article about graceful way to do monkey-patching.
And small advertising of my lib for monkey-patching: monkey-punch
Option 4: Attach new tag
You can attach js files with:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);
You're also able to remove dom elements (scripts, styles) and attach new at anytime.
Hi recently I have to implement a git API for a node module, so we can have version control through programmatic interface. I came upon this post to find some good modules that I can use.
However, after playing around with some of them, I realized that none of them provide the feature of querying the commit history of a single file (like calling 'git log --follow '). I would like to extend that feature into my module but since I have no experience before, does anyone know where I should start?
The libraries you mentioned should be a good starting point. Take node-git's lib/git.js file for example. There you can find the following lines:
// Call the native git binary
Git.prototype.call_git = function(prefix, command, postfix, options, args, callback) {
// ...
This is a good starting point to understand how the author maps Node functions on system calls and and allows the callback to work with the output.
I would start a fork of the project. Look for the log function in the same file, which starts like
Git.prototype.log = function(commit, path, options, callback) {
Copy the function, give it a proper name and try to adopt it to meet your needs.
If you succeed and like to help, you could start a pull request on GitHub to help the author and add the functionallity to the official project.
I would do it this way. I hope this helps.
I load lot of JavaScript From My DB for validation and for Costume Validation which can be Uploaded through My Customer so i want to validate whether the given Javscript is valid or Not While Rendering it on my page i am using MVC 3.0 razer view engine
Please help me finding a way fix it
Thanks
Ashies
Your task is simply not recommended. Render JavaScript code directly from the database is dangerous because you are leaving the doors wide open to XSS attacks.
However, yes, you can validate JSCode normally with JSLint.
There is a plugin for visual studio, and of course there might be a way to use the functionality packed in the JSLint DLL so you can check your JavaScript.
This two posts might put you in the "right" direction. (I still have to say that rendering user entered JS code is fundamentally wrong)
http://www.codeproject.com/Articles/21438/JSLint-VS-JavaScript-Verifier-for-Visual-Studio
http://blog.outsharked.com/2011/08/sharplinter-command-line-tool-for.html
I assume that you are working with Visual Studio 2010/2012.
As Adrian Salazar said:
Your task is simply not recommended. Render JavaScript code directly from the database is dangerous because you are leaving the doors wide open to XSS attacks.
That being said I would highly recommend rethinking your current design. If you're planning on doing so, you should have a look at Web Essentials which is a plugin available from NuGet. This has JSHint integrated which will check your Javascript after saving a file or on building your application within Visual Studio.
Also downloadable as installer:
http://visualstudiogallery.msdn.microsoft.com/6ed4c78f-a23e-49ad-b5fd-369af0c2107f
or for 2012:
http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6
Javascript syntax checking is tricky because there is so much scope for generating silent run-time errors based on how primitive are handled (for example).
There are verifiers like JSLint available and you can build your own techniques for verification.
I use the following structure for javasript files (using jquery) setting a class ("scriptVerified") on the body tag if the script completely runs - which can quickly tell you if the script looks syntactically OK. But event handlers can still go wrong when the event is fired.
#AdiranSalazar's security warning is worth listening to.
$(document).ready(function () {
pageScript.Init();
});
var pageScript =
{
Init: function()
{
pageScript.CleanUp();
pageScript.RegisterHandlers();
pageScript.Start();
pageScript.Final();
},
CleanUp: function()
{
//put page cleanup stuff in here
},
RegisterHandlers: function()
{
//register event handlers in here
},
Start: function()
{
//put page js code in here
},
Final: function () {
$("body").addClass("scriptVerified"); //add class to body to say this has run
}
};