I am trying to load external javascript in the pre-request tab of postman request by following the steps mentioned in https://blog.postman.com/adding-external-libraries-in-postman/ but seems like it is not working. Below is the code I am trying and it is not loading. I am not sure what is wrong and what is not working
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/chance/1.1.8/chance.min.js", (err, res) => {
//convert the response to text and save it as an environment variable
pm.collectionVariables.set("chancejs_library", res.text());
eval(pm.collectionVariables.get("chancejs_library"));
console.log(this.chance().string()) // --> not working
console.log(this.chance()) // --> not working
console.log(this.Chance()) // --> not working
console.log(this.Chance().string()) // --> not working
})
In all the above cases, I get the same error
ReferenceError: chance is not defined
It is indeed chancejs's "fault". I don't know what kind of "environment"/"runtime" Postman is providing for running js in general, but it seems that Chance() instance is never created in it - no matter if using eval() or IIFE... Last lines of chance.js are to blame (starting with the comment "// CommonJS module" where - to my understanding - instantiation happens).
So I figured a dirty "hack" which makes chancejs usable in Postman:)
I took version 1.1.9 of chancejs from github, then I simply added "else" statement to one of those "ifs" from instantiation section:
// if there is a importsScrips object define chance for worker
// allows worker to use full Chance functionality with seed
if (typeof importScripts !== 'undefined') {
chance = new Chance();
self.Chance = Chance;
}
else {
chance = new Chance();
}
Then I followed Load a library from a variable section from https://blog.postman.com/adding-external-libraries-in-postman/ (when setting chancejs collection variable I obviously had to use the "hacked" version of the chancejs)
var chancejs = pm.collectionVariables.get('chancejs');
(new Function(chancejs))();
// testing if this works by calling sentence() method :)
console.log(chance.sentence());
Seems to work :)
Related
I have a classic asp project. In one of my pages i have to call a javascript function. That call does not have any problem and works fine on my test server (not localhost, just a server to test he project). But when i deploy it to the actual server, that function does not work. I call this function in onload event.
That function has this type of lines (i cannot write the whole code, because of the company that i work for, does not allow it)
document.getElementById("R6C2_1").style.display = 'block'
document.getElementById("R6C2_2").style.display = 'none'
....
When I try to debug it on IE10, i got "Unable to get property 'style' of undefined or null reference" error. After that, the elements in javascript function are not load. They are not seen on the page.
My main problem is, as i mentioned before differences between servers. I do not understand why it works on one server, but not on another server.
While it's not possible to determine the issue from this information alone, you should look into:
Whether the elements you're looking for actually exist when the code is invoked (use browser debug / breakpoints to look at the page the moment the code is invoked).
If they exist, check if they have the ID you expect (e.g R6C2_1) - if not, why? who creates these IDs? could be a server configuration issue.
Do a debug using the app from each server, and look at the page / DOM, see if there are differences or check if the code is invoked at different times.
These could lead you to pinpoint the issue. Good luck!
In case the elements just take time to be created, you can just wait until they are present:
function ExecuteWhenExists() {
var R6C2_1 = document.getElementById("R6C2_1");
var R6C2_2 = document.getElementById("R6C2_2");
if (R6C2_1 && R6C2_2) {
R6C2_1.style.display = 'block';
R6C2_2.style.display = 'none';
} else {
window.setTimeout(ExecuteWhenExists, 100);
}
}
ExecuteWhenExists();
This will not crash when the elements do not exist, and will just keep trying to execute in a non-blocking way (polling every 0.1 seconds) until they exist.
I'm writing a bootstrap firefox extension. Using firefox developer edition v36.2a
I have two problems that seem related, which I don't understand. The first one, mere annoyance:
my bootstrap Console.utils.imports a js file which loads my application (creates a namespace object and imports all other js files as properties on the namespace. All other files include this same namespace file and thus have access to each other. They even store state and everything works much similar to how node caches modules, eg it seems there is only one object of every class which is shared throughout the whole application. Now, this happens:
my namespace file does:
namespace.console = Components.utils.import( 'you know the one/console.jsm' )
namespace.Services = Components.utils.import( 'you know the one/Services.jsm')
namespace.Cu = Components.utils
Now in another file that imports this file, I get the namespace object, but namespace.Cu will be undefined. console.log( namespace ) is fine however and shows me Cu, that I can expand and see all its properties and so on... All other things (console, Services, my own classes) are fine, but trying Cc, Ci etc from Components -> undefined.
In another place in my app I have a function (in file A) which returns an array of nsiDomWindows. A function in file B calls it and when it arrives, similar story: in console all looks fine, Array with ChromeWidows that I can look at. But it's no longer an array actually and is of type object and array[ 0 ] is undefined. If I put both classes in the same file they're fine.
For further confusion, I think I have already used this method in another file and all was fine:
// A.js
//
function A()
{
b = new B()
c = new C()
let windows = b.windowList () // works fine, yields an actual valid array
// with valid windows inside
c.doSomething() // broken, see below
c.doSomething( windows ) // passing it as a parameter
// doesn't help, still broken
}
// B.js
//
function B()
{
this.windowList = function windowList()
{
let result = []
// get open windows from nsiWindowMediator
// foreach...
//
result.push( nsiDomWindow )
console.log( typeof result ) // Array -> it's completely valid here
return result
}
}
// C.js
//
function C()
{
this.b = new B()
this.doSomething = function doSomething( windows )
{
if( ! windows )
windows = this.b.windowList()
console.log( windows ) // in the console shows:
// Array[ ChromeWindow -> about:home ]
// I can inspect all it's properties, looks ok
console.log( typeof windows ) // object
console.log( windows.constructor.name ) // undefined
console.log( windows[ 0 ] ) // undefined
// looping over the object properties shows that it does
// have 1 property called '0' which points at undefined
// note: there was only one open window in the array.
}
}
// Note: the order in which I use Components.utils.import on these is B, C, A
I also wondered if this had to do with security measures in gecko, but no wrapper objects are to be seen anywhere, and afaik they should only shield content code from chrome code (this is all chrome code).
It's the kind of bugs that frustrates me, because I can't think of one sensible reason why the return value of a function shouldn't be the same thing on two sides of the call.
Lucky enough there is a workaround, I will have my make file concatenate all my js files and be done with Components.utils once and for all. Seems the less of the mozilla API I have to use, the happier and more productive I'll be.
I'm seeing errors from mozilla code as well. I just had an error saying "shouldLog is not a function" in Console.jsm. This function is clearly defined higher up in that file. The line that throws the error is an anonymous function that is being returned. That should inherit the scope without a doubt, but it doesn't. It might be that something is mangling return values and that this is related.
I filed a bug on bugzilla with a sample addon attached which demonstrates the first of the problems mentioned above.
update:
I'm sorry, I confused two things. I just figured out what happened in the first case of Cu not being available. I just loaded the file in which the problem happens before adding Cu to my namespace and since I did const { console, Services, Cu } = namespace on the global scope, this actually got evaluated before the property was made. The confusing part about it is that the console keeps references, not copies of the objects it shows you (an unfortunate design choice if you ask me) logging the namespace before the code in question gives you a view on it's state later on, which I missed to take into consideration.
That still doesn't explain how one function can return a perfectly sound value to a receiving function who receives something else, or how a function declared in Console.jsm doesn't seem to exist anymore in a function who inherits it's scope.
All in all, the first problem hasn't got anything to do with the others. I can't however create a reproducible small addon to illustrate the other 2. If I think of a way I'll upload it.
Btw: The pitfall by console can be easily seen (put the following in a javascript scratchpad):
let a = { some: "value" }
console.log( a )
delete a.some
// output: Object { }
For debugging purposes (usually it's main purpose) console has it's limits, and it usually better to set a breakpoint in a debugger or use JSON.stringify
I think I've narrowed all the fore mentioned problems to unloading uncorrectly. I had eventlisteners that I didn't remove and when they fired, objects or scopes can be invalidated.
Using the Extension Auto-Installer somewhat made these problems more severe because when reloading the addon when it hasn't properly unloaded creates an unreliable state of the addon code.
The shouldLog is not a function was because I thought that I had to unload all modules that I loaded with Components.utils.unload, so I unloaded Console.jsm.
After fixing that plus wrapping all the entry points into my software in try-catch blocks, things now run smoother. I now rarely have to uninstall the addon and restart firefox after updating the code.
There's nothing like a few fun days of debugging...
I didnt read it all but:
I think the first issue is you are importing it wrong.
If you want to bring it to a certain namespace to the exported var from Cu.import you should do it like this:
Cu.import('resource://gre/modules/ctypes.jsm', namespace);
No need for the var blah = Cu.import
Console.jsm and Services.jsm export a var named te same thing.
You can even just do Cu.import('rsource://gre/modules/ctypes.jsm') and start using it like ctypes.blah
Also to get access to Cu do this:
var {Cu: utils, Cr: results} = Components
Next i think if you change the module in one scope, it will not change in other scopes until you do Cu.import again in that scope.
I read a lot about Express / SocketIO and that's crazy how rarely you get some other example than a "Hello" transmitted directly from the app.js. The problem is it doesn't work like that in the real world ... I'm actually desperate on a logic problem which seems far away from what the web give me, that's why I wanted to point this out, I'm sure asking will be the solution ! :)
I'm refactoring my app (because there were many mistakes like using the global scope to put libs, etc.) ; Let's say I've got a huge system based on SocketIO and NodeJS. There's a loader in the app.js which starts the socket system.
When someone join the app it require() another module : it initializes many socket.on() which are loaded dynamically and go to some /*_socket.js files in a folder. Each function in those modules represent a socket listener, then it's way easier to call it from the front-end, might look like this :
// Will call `user_socket.js` and method `try_to_signin(some params)`
Queries.emit_socket('user.try_to_signin', {some params});
The system itself works really well. But there's a catch : the module that will load all those files which understand what the front-end has sent also transmit libraries linked with req/res (sessions, cookies, others...) and must do it, because the called methods are the core of the app and very often need those libraries.
In the previous example we obviously need to check if the user isn't already logged-in.
// The *_socket.js file looks like this :
var $h = require(__ROOT__ + '/api/helpers');
module.exports = function($s, $w) {
var user_process = require(__ROOT__ + '/api/processes/user_process')($s, $w);
return {
my_method_called: function(reference, params, callback) {
// Stuff using $s, $w, etc.
}
}
// And it's called this way :
// $s = services (a big object)
// $w = workers (a big object depending on $s)
// They are linked with the req/res from the page when they are instantiated
controller_instance = require('../sockets/'+ controller_name +'_socket')($s, $w);
// After some processes ...
socket_io.on(socket_listener, function (datas, callback) {
// Will call the correct function, etc.
$w.queries.handle_socket($w, controller_name, method_name, datas);
});
The good news : basically, it works.
The bad news : every time I refresh the page, the listeners double themselves because they are in a loop called on page load.
Below, this should have been one line :
So I should put all the socket.on('connection'...) stuff outside the page loading, which means when the server starts ... Yes, but I also need the req/res datas to be able to load the libraries, which I get only when the page is loaded !
It's a programing logic problem, I know I did something wrong but I don't know where to go now, I got this big system which "basically" works but there's like a paradox on the way I did it and I can't figure out how to resolve this ... It's been a couple of hours I'm stuck.
How can I refacto to let the possibility to get the current libraries depending on req/res within a socket.on() call ? Is there a trick ? Should I think about changing completely the way I did it ?
Also, is there another way to do what I want to do ?
Thank you everyone !
NOTE : If I didn't explain well or if you want more code, just tell me :)
EDIT - SOLUTION : As seen above we can use sockets.once(); instead of sockets.on(), or there's also the sockets.removeAllListeners() solution which is less clean.
Try As Below.
io.sockets.once('connection', function(socket) {
io.sockets.emit('new-data', {
channel: 'stdout',
value: data
});
});
Use once instead of on.
This problem is similar as given in the following link.
https://stackoverflow.com/questions/25601064/multiple-socket-io-connections-on-page-refresh/25601075#25601075
So, as a sort of exercise for myself, I'm writing a little async script loader utility (think require.js, head.js, yepnope.js), and have run across a little bit of a conundrum. First, the basic syntax is like this:
using("Models/SomeModel", function() {
//callback when all dependencies loaded
});
Now, I want to know, when this call is made, what file I'm in. I could do it with an ajax call, so that I can mark a flag after the content loads, but before I eval it to mark that all using calls are going to be for a specific file, then unset the flag immediately after the eval (I know eval is evil, but in this case it's javascript in the first place, not json, so it's not AS evil). I'm pretty sure this would get what I need, however I would prefer to do this with a script tag for a few reasons:
It's semantically more correct
Easier to find scripts for debugging (unique file names are much easier to look through than anonymous script blocks and debugger statements)
Cross-domain requests. I know I could try to use XDomainRequest, but most servers aren't going to be set up for that, and I want the ability to reference external scripts on CDN's.
I tried something that almost got me what I needed. I keep a list of every time using is called. When one of the scripts loads, I take any of those using references and incorporate them into the correct object for the file that just loaded, and clear the global list. This actually seems to work alright in Firefox and Chrome, but fails in IE because the load events seem to go off at weird times (a jQuery reference swallowed a reference to another type and ended up showing it as a dependency). I thought I could latch on to the "interactive" readystate, but it doesn't appear to ever happen.
So now I come asking if anybody here has any thoughts on this. If y'all want, I can post the code, but it's still very messy and probably hard to read.
Edit: Additional usages
//aliasing and multiple dependencies
using.alias("ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", "jQuery");
using(["jQuery", "Models/SomeModel"], function() {
//should run after both jQuery and SomeModel have been loaded and run
});
//css and conditionals (using some non-existant variables here)
using.css({ src: "IEFix", conditionally: browser === "MSIE" && version < 9 });
//should include the IEFix.css file if the browser is IE8 or below
and to expound more on my response below, consider this to be file A (and consider the jquery alias from before to be there still):
using(["jQuery", "B"], function() {
console.log("This should be last (after both jQuery and B have loaded)");
console.log(typeof($));
});
Then this would be B:
using("C", function() {
console.log("This should be second");
});
And finally, C:
console.log("This should be first");
The output should be:
This should be first
This should be second
This should be last (after both jQuery and B have loaded)
[Object Object]
Commendable that you are taking on such an educational project.
However, you won't be able to pull it off quite the way you want to do it.
The good news is:
No need to know what file you are in
No need to mess with eval.
You actually have everything you need right there: A function reference. A callback, if you will.
A rough P-code for your using function would be:
function using(modules, callback) {
var loadedModules = []
// This will be an ajax call to load things, several different ways to do it..
loadedModules[0] = loadModule(modules[0]);
loadedModules[1] = loadModule(modules[1]);
// Great, now we have all the modules
// null = value for `this`
callback.apply(null, loadedModules);
}
I work on an app with a javascript/html front-end and a back-end REST service. I mostly work on the back end service, but I'm attempting to add javascript unit tests to the build. I had someone help me with the javascript testing framework setup, using phantomjs, qunit, and jstestrunner, all referenced from Maven.
I wrote a trivial unit test for a module (we'll call it "data.daily.js") that begins like this:
Data.Daily = new Function();
Data.Daily.prototype = {
Just to be clear, this code runs every day in production, and appears to work fine in all major browsers (FF, IE, and Chrome).
The test looks like this:
requirejs.config({ shim: { 'data.daily': ['config'] } });
require(['data.daily'], function() {
'use strict';
module('data.daily');
test('data.daily.test.initialize', function() {
var dataDaily = new Data.Daily();
dataDaily.initialize(Config.AJAX_DAILY_DATA_BASE_URL, Config.MOCKDATA_AJAX_DAILY_DATA_BASE_URL);
deepEqual(dataDaily.getData(), {}, "object is \"" + JSON.stringify(dataDaily.getData()) + "\", but it should be empty object");
});
});
When I run this test, it fails like this:
ReferenceError: Can't find variable: Data, source: http://localhost:9080/data.daily.js:5
[data.daily] data.daily.test.initialize: failed: 1 passed: 0
Died on test #1 at http://localhost:9080/js/qunit.js:425
at http://localhost:9080/js/data.daily.test.js:17
at http://localhost:9080/js/require.js:1682
at http://localhost:9080/js/require.js:983
at http://localhost:9080/js/require.js:1194
at http://localhost:9080/js/require.js:129
at http://localhost:9080/js/require.js:1237
at each (http://localhost:9080/js/require.js:58)
at http://localhost:9080/js/require.js:1238
at http://localhost:9080/js/require.js:1043
at http://localhost:9080/js/require.js:1224
at http://localhost:9080/js/require.js:882
at callGetModule (http://localhost:9080/js/require.js:1249)
at http://localhost:9080/js/require.js:1578
at http://localhost:9080/js/require.js:1703: Can't find variable: Data, source: ReferenceError: Can't find variable: Data
The only way I can find to get this test working is to change "data.daily.js" in this way, adding a line before the existing lines:
var Data = {};
Data.Daily = new Function();
Data.Daily.prototype = {
Now I have to say that this looks logical to me, but the fact remains that the existing code works fine in all the major browsers. This code only started failing when referenced from the test.
Note that I also tried changing the test script instead, adding the "var Data = {}" line before the "var dataDaily = new Data.Daily()" line, but that had no effect.
So, can anyone explain what is going on here? Why does the original code work if it fails in the test. Is there something funky about how "require.js" works that makes this happen? Why didn't the test work by adding the line in the test, instead of the CUT (code under test)?
Ok, I've managed to resolve this.
The assignment is actually present in the existing production code, I just didn't think to look in ".html" files for it before. When I didn't find it in ".js" files, I thought something else was going on.
The reason it didn't work to put the line in the test script instead was because I was putting the line in the wrong place. The error actually occurs at configuration time, not when the test itself is executed, so the assignment had to be before the "requirejs.config()" call. Now the test works, without having to modify the CUT.