Meteor: unreliable session variable? - session

I'm making a service where there are no user accounts, and I want to restrict by what page I'm visiting.
So each page is a "box", and on each "box" I have a bunch of "files".
I've published the relevant info in server/publications.coffee
Meteor.publish 'files', (boxId)->
console.log boxId
return Files.find({boxId:boxId})
My file for 'box' has a subscription handle:
#filesHandle = Meteor.subscribe 'files', Session.get('currentBoxId')
And the currentBoxId is stored in the session variable.
Here's the crazy part: I expect this to work, and it does on the first time I start the server. The console.log in the first bit of code prints the proper ID. Then, all of a sudden the console log suddenly starts returning "null", even when I console.log the session var in the browser console, it returns correctly.
I feel like there's some kind of loading asynchrony issue here, but I have no idea what's going on.
Any clues?

Ah, figured it out. The template can be rendered before the session variable is set, apparently. Usually you put your collection handles in the main.js file in the application scope, but this doesn't work if the subscription depends on session variables.
I did the following:
Template.boxPage.created = ()->
#filesHandle = Meteor.subscribe 'files', Session.get('currentBoxId')

Related

How and in what way do content scripts share content scoped variables across different web pages?

There are some key parts of the MDN content script documentation I am having trouble understanding regarding variable scope:
There is only one global scope per frame, per extension. This means that variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.
This paragraph may also be relevant (my italics) given the questions below:
... you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
I assume (testing all this has proved difficult, please bear with me) that this means:
The content script code will be run every time a new page is loaded that matches the URLs provided in manifest.json (in my case "matches": [<"all_urls">]
The content script code will run every time a page is refreshed/reloaded.
The content script code will not be run when a user switches between already open tabs (requires listening to window focus or tabs.onActivated events).
The variables initialized on one page via the content script share a global scope with those variables initialized by the same content script on another page.
Given the following code,
background-script.js:
let contentPort = null
async function connectToActiveTab () {
let tab = await browser.tabs.query({ active: true, currentWindow: true })
tab = tab[0]
const tabName = `tab-${tab.id}`
if (contentPort) {
contentPort.disconnect()
}
contentPort = await browser.tabs.connect(tab.id, { name: tabName })
}
// listening to onCreated probably not needed so long as content script reliably sends 'connecToActiveTab' message
browser.tabs.onCreated.addListener(connectToActiveTab)
browser.runtime.onMessage.addListener(connectToActiveTab)
content-script.js
let contentPort = null
function connectionHandler (port, info) {
if (contentPort && contentPort.name !== port.name) {
// if content port doesn't match port we have changed tabs/windows
contentPort.disconnect()
}
if (!contentPort) {
contentPort = port
contentPort.onMessage.addListener(messageHandler)
}
}
async function main () {
// should always be true when a new page opens since content script code is run on each new page, testing has shown inconsistent results
if (!contentPort) {
await browser.runtime.sendMessage({ type: 'connectToActiveTab' })
}
}
browser.runtime.onConnect.addListener(connectionHandler)
main()
And from assumptions 1 and 4, I also assume:
The existing contentPort (if defined) will fire a disconnect event (which I could handle in the background script) and be replaced by a new connection to the currently active tab each time a new tab is opened.
The behaviour I have seen in Firefox while testing has so far been a bit erratic and I think I may be doing some things wrong. So now, here are the specific questions:
Are all of my 5 assumptions true? If not, which ones are not?
Is firing the disconnect() event unnecessary, since I should rely on Firefox to properly clean up and close existing connections without manually firing a disconnect event once the original contentPort variable is overwritten? (the code here would suggest otherwise)
Are the connect() methods synchronous, thus negating the need for await and asynchronous functions given the example code?
The tabs.connect() examples don't use await but neither the MDN runtime or connect docs explicitly say whether the methods are synchronous or not.
Thanks for taking the time to go through these deep dive questions regarding content script behaviour, my hope is that clear and concise answers to these could perhaps be added to the SO extension FAQ pages/knowledge base.

Creating a simple, basic page object in Nightwatch.js

Ok, so I've read up on the use of page_objects in nightwatch.js, but I'm still getting issues with it (which I'm convinced is due to something obvious and/or simple).
Using http://nightwatchjs.org/guide/#page-objects as the guide, I added the the file cookieremoval.js in my page_objects folder.
module.exports = {
elements: {
removeCookies: {
selector: '.banner_continue--2NyXA'
}
}
}
In my nightwatch.conf.js file I have;
page_objects_path: "tests/functional/config/page_objects",
And in my test script I have;
module.exports = {
"/cars/road-tax redirects to /car-tax/ ": browser => {
browser.url(browser.launch_url + browser.globals.carReviews)
.assert.urlEquals(browser.launchUrl + "/car-reviews/")
.waitForElementPresent('#cookieRemove', 3000)
.click('#cookieRemove')
.end();
},
};
However, when I run the test, I keep getting an error reading;
Timed out while waiting for element <#cookieRemove>
Any ideas why this is not working?
Many thanks
First of all, you never instantiated your page object. You're asking the browser object to search for an unknown element, that's why it's timing out. Your code should look something like this in your test script: var cookieRemoval = browser.page.cookieremoval(); then use this object to access those variables and functions in your page object. For example, if you wanted to access the remove cookie element, then you would do this cookieRemoval.click('#removeCookies');.
Secondly, you will have to know when to use the global browser object and when to use your page object. If you need to access something within your page object, obviously use the page object to call a function or access a variable. Otherwise, browser won't know the element you're looking for exists. Hope this help you out, I would definitely spend some more time learning about objects and specifically how they're used in nightwatch.js.

Parse.User.current(), globals etc

I am new to Express and Parse. I am trying to make a simple modification to the Anyimg cloud tutorial. I would like to display the default home page only if the user is authenticated. If I use Parse.User.authenticated(), I get:
The error was TypeError: Object function (){e.apply(this,arguments)} has no method 'authenticated'
at app.js:33:18
at main.js:1:1
Parse.User.current() compiles with no error, but the code does not work. What am I missing? I have tried literally over 60 different options over the last 3 days with no success.
I also tried to declare a GLOBAL from within user.js and that did not work. I did a require cloud/user from within app.js and that did not help at all.
I hope someone can help. It appears that Parse tutorials (outside parse.com) from about a year ago break.
On the other hand, I wanted to display the login page (not default) upon logout. I got it done in less than 10 minutes.
The correct way to do this would be:
var currentUser = Parse.User.current();
if (currentUser) {
// logged in
} else {
// not logged in
}
Parse.User.current() returns the current user, or undefined if not logged in.
as seen here: https://parse.com/docs/js_guide#users-current
As mentioned above, I already had code that was similar to Fosco's. However, the var statement was not in the scope of the function as I was trying out o. I just moved it in and it all works. Thanks to everyone for looking into this.

Meteor 0.5.9: replacement for using Session in a server method?

So, I was attempting to do something like the following:
if(Meteor.isServer){
Meteor.methods({connect_to_api: function(vars){
// get data from remote API
return data;
}});
}
if(Meteor.isClient){
Template.myTpl.content = function(){
Meteor.call('connect_to_api', vars, function(err,data){
Session.set('placeholder', data);
});
return Session.get('placeholder');
};
}
This seemed to be working fine, but, of course, now breaks in 0.5.9 as the Session object has been removed from the server. How in the world do you now create a reactive Template that uses a server-only (stuff we don't want loading on the client) method call and get data back from that Method call. You can't put any Session references in the callback function because it doesn't exist on the server, and I don't know of any other reactive data sources available for this scenario.
I'm pretty new to Meteor, so I'm really trying to pin down best-practices stuff that has the best chance of being future-proof. Apparently the above implementation was not it.
EDIT: To clarify, this is not a problem of when I'm returning from the Template function. This is a problem of Session existing on the server. The above code will generate the following error message on the server:
Exception while invoking method 'connect_to_api' ReferenceError: Session is not defined
at Meteor.methods.connect_to_api (path/to/file.js:#:#)
at _.extend.protocol_handlers.method.exception ... etc etc
Setting the session in the callback seems to work fine, see this project I created on github: https://github.com/jtblin/meteor_session_test. In this example, I return data in a server method, and set it in the session in the callback.
There are 2 issues with your code:
1) Missing closing brace placement in Meteor.methods. The code should be:
Meteor.methods({
connect_to_api: function(vars) {
// get data from remote API
return data;
}
});
2) As explained above, you return the value in the session, before the callback is completed, i.e. before the callback method had the time to set the session variable. I guess this is why you don't see any data in the session variable yet.
I feel like an idiot (not the first time, not the last). Thanks to jtblin for showing me that Session.set does indeed work in the callback, I went back and scoured my Meteor.method function. Turns out there was one spot buried in the code where I was using Session.get which was what was throwing the error. Once I passed that value in from the client rather than trying to get it in the method itself, all was right with the world.
Oh, and you can indeed order things as above without issue.

rails session_store odd behaviour

I am using active_record_store in a rails application which is storing this in session session[:email] = "email#address.com"
now this works fine in the action. but when this action gets over and is redirected to another page, which also accesses the same session[:email] I get an error
undefined method `eq' for nil:NilClass
this should probably mean that i am trying to compare values at some place i am not allowed to. but i cannot see anything like that in the code.
This looks like an old question, but I was just having the same problem and had to figure it out on my own, and thought I would post the solution up here for anyone else that runs into this. It's not very well documented, but to get this to work you have to add:
config.action_dispatch.session_store = :active_record_store
to application.rb, and
Application.config.session_store :active_record_store
to config/initializers/session_store.rb. Then, you have to do:
rake db:sessions:create
and:
rake db:migrate
Then, you have to restart your rails server. I think it was the db:sessions:create step that tripped up the original poster. Not only does that database table have to be laid out the way rails is expecting (that is, with an 'id' column, which is the actual cause of this error, I think), but also the current session has to have a valid ID. Hence the need to create the table and re-start the server, or potentially empty the table if it exists.

Resources