I am creating a web app which I plan to deliver both from a standard web site and as an NWJS standalone application. In NWJS, I can use the require command, but not in a browser. I can wrap my command in an if statement:
<script>
if (typeof require === "function") {require('nwjs-osx-menu')(window)}
</script>
Are there other ways that would be considered better practice?
EDIT: following #Kuf's suggestion
<script>
if (typeof require === "function") {
try{
require('nwjs-osx-menu')(window)
} catch (error) {}
}
</script>
Update
If the only difference is loading that library then your code seems fine.
original post
There is a web client require module so that might be a bit risky. I used the following:
function is_nwjs(){
try{
return (typeof require('nw.gui') !== "undefined");
} catch (e){
return false;
}
}
process.__nwjs
if nwjs exist, the value will 1
My limited understanding is that if process is defined, you are in NWJS, and have access to fields such as process.versions['nw-flavor'].
Related
I've read the feathersjs documentation, but after doing a find method in a service I realized that if I don't give any query parameters, the service returns all the data, which is something I don't want. How can I define a hook to validate that there are at least one query parameter in order to proceed; otherwise, send back a 403 error (bad request).?
I have doubts in the way to do it I tried this:
app.service('myService')
.before(function(hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
})
.find({
query: {
$sort: {
year: -1
}
}
})
And I tried in hook file on hooks this (that seemed really desperate & | stupid):
function noparams (hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
}
module.exports = {
before: {
find: [ noparams(this) ] ...
}
}
but it does not compile (I don't know what to send as a parameter there), and the examples seemed to be for pre 2.0 version and on top of that the code I found seemed to be in the app.js, but all is differently coded using feathers-cli, so the examples, even in the book, aren't against the scaffolded version, which is confusing because they shows the code in a different file were should be.
Thanks.
I ended using a before hook, so the code used is this:
const errors = require('feathers-errors');
module.exports = function () {
return function (hook) {
if(hook.method === 'find'){
if (hook.params.query.name === undefined || hook.params.query.length == 0){
throw new errors.BadRequest('Invalid Parameters');
}else{
return hook;
}
}
}
};
If have used feathers-cli to generate your application (feathers v2.x) you don't need to do anything else. If is an earlier version you maybe need to add the Express error handler and it is pointed out in the documentation|Errors|REST.
Thanks.
I am updating data in SuiteCRM using set entry call. But my issue is that the call is asynchronous and what I want it to be synchronous. My code in node js. Kindly help me out.
CRM.set_entry("Cases",array_to_set_entry[i],function(err1, res1, body1){
console.log("I am inside crm set_entry");
if (body1 && typeof body1.id !== constant.undefined) {
console.log("checkCRM")
}
else {
console.log("checkCRM failed")
} });
I searched stack overflow for solutions. I found async.queue() as a possible solution but still i am not getting how to use it in my case.
Is there a way (preferably Firefox or Chrome) to log all the DOM methods invoked/properties modified by a Web app?
I need this to understand some of the working of web apps whose code I don't have in non-minified version.
I understand that this won't give me the complete picture, but I am more interested in the web app's interaction with the browser for my purpose.
You can log all method calls for specific class of objects by wrapping all of its methods with a custom logging function:
var originalMethod = SomeObject.prototype.someMethod;
SomeObject.prototype.someMethod = function() {
//log this call
originalMethod.apply(this, arguments);
}
I've created a function that hooks up such wrappers to all (non-inherited) methods of given class and logs all calls to the console:
function logMethodCalls(className) {
function wrapMethod(className, methodName, prototype) {
var orgMethod = prototype[methodName];
return function() {
window.console.debug('%c'+className+'::%c'+methodName, 'color: #FBB117; font-weight: bold', 'color: #6F4E37', {
details: {
scope: this,
arguments: arguments
}
});
return orgMethod.apply(this, arguments);
};
}
if(!window[className] || typeof window[className] !== 'function') {
window.console.error('Invalid class name.');
return;
}
var prototype = window[className].prototype;
for(var i in prototype) {
if(prototype.hasOwnProperty(i)) {
if(typeof prototype[i] === "function") {
prototype[i] = wrapMethod(className, i, prototype);
}
}
}
}
I'm running it like this:
["Document", "DocumentFragment", "Element", "Event", "HTMLElement", "HTMLDocument", "Node", "NodeList", "Window"].forEach(function(i){
logMethodCalls(i);
});
You can customise the array above to track only classes that you are interested in.
The output looks like this:
To be perfectly honest there is so much output that I don't think this type of debugging may be usable. You can try extending this solution even more by observing all properties (e.g. by defining getters and setters or proxies for all objects), but this will get even more messy.
Great idea! Tracking DOM changes may be useful when trying to understand how website/app works, but also while searching for performance bottlenecks (DOM access is expensive).
I haven't found extension that does exactly what you are asking for, so I've created one. You can install DOMListener from Chrome Web Store.
DOMListener extension uses MutationObserver to catch all DOM changes and outputs friendly messages to the DevTools console. Note that I'm using console.debug() so you can easily filter these messages out:
Code is available on GitHub. If you prefer to avoid installing the extension or you want to get a similar output in Firefox, simply grab the DOMListener.js file and run it in the console.
I am using the following node module for validation: https://github.com/chriso/node-validator
Now, suppose I want to check on an user input like this check('abc').isInt(); I noticed that it basically throws an error!
I am pretty new with node.js but it seems to me that having to use try{}catch(e){} blocks every time I need to check on a user input is a bit on an overkill.
wouldn't it make more sense to have something like
if (check('abc').isInt()) {
// Do things here
next(null, stuff_I_want_to_return)
} else next(error);
instead of
try{
check('abc').isInt()
next(null, stuff_I_want_to_return)
} catch(e) { next(e); }
?? I have no idea, please clarify on what is the best approach to have in this case. Thanks in advance.
Their docs say you can do this
var Validator = require('validator').Validator;
var v = new Validator();
v.error = function(msg) {
console.log('Fail');
}
v.check('abc').isInt(); //'Fail'
That way you won't have to do try catch
Check module core-util-is providing functions introduced in Node v0.12.
In your case, method isNumber would be helpful
It's still fairly common in Node.js for synchronous functions to throw as they don't usually have a callback to pass an error to. But, they still need some way to deliver it to calling code and return error; would generally be an unexpected choice.
Though, the documentation for node-validator does include an example for extending Validators with a getErrors() method under "Error Handling."
Validator.prototype.error = function (msg) {
this._errors.push(msg);
return this;
}
Validator.prototype.getErrors = function () {
return this._errors;
}
Which could be used to report errors without throw:
var validator = new Validator();
if (validator.check('abc').isInt()) {
next(null, ...);
} else {
next(validator.getErrors());
}
Note: The _errors property should already be defined after using .check().
In a Chrome extension, a script may be included as a content script or background script.
Most stuff it does is the same, but there are some would vary according to different context.
The question is, how could a script tell which context it is being run at?
Thank you.
I think this is a fairly robust version that worked in my initial tests and does not require a slower try catch, and it identifies at least the three primary contexts of a chrome extension, and should let you know if you are on the base page as well.
av = {};
av.Env = {
isChromeExt: function(){
return !!(window['chrome'] && window['chrome']['extension'])
},
getContext: function(){
var loc = window.location.href;
if(!!(window['chrome'] && window['chrome']['extension'])){
if(/^chrome/.test(loc)){
if(window == chrome.extension.getBackgroundPage()){
return 'background';
}else{
return 'extension';
}
}else if( /^https?/.test(loc) ){
return 'content';
}
}else{
return window.location.protocol.replace(':','');
}
}
};
Well I managed to work out this:
var scriptContext = function() {
try {
if (chrome.bookmarks) {
return "background";
}
else {
return "content";
}
}
catch (e) {
return "content";
}
}
It's because an exception would be thrown if the content script tries to access the chrome.* parts except chrome.extension.
Reference: http://code.google.com/chrome/extensions/content_scripts.html
The best solution I've found to this problem comes from over here.
const isBackground = () => location.protocol === 'chrome-extension:'
The background service worker at Manifest v3 does not contain a window.
I use this as part of my extension error handling which reloads the content scripts, when i receive an Extension context invalidated error:
...
if (!self.window) {
console.warn('Background error: \n', error);
} else {
location.reload();
}
...