Debugging Javascript (and Facebook Login) - javascript

I am not good with JS :) I am messing around with adding the Facebook Login to my site here at http://www.comehike.com and on top right you can see that the FB login button renders, but if you click it, it doesn't work.
I tried putting the button into the body of the page and it actually worked. So my sense is that its some JS issue that caused the problem. How do I debug it in Firebug or another tool? I am just not fluent maneuvering in these technologies.
Any help would be appreciated. All I really want to do is make the FB login button click-able in the header :)
Thanks,
Alex

Use a console (Firebug, for instance) and the problem is pretty clear.
Uncaught ReferenceError: FB is not defined www.comehike.com:94
FB.login() called before calling FB.init(). all.js:3
My guess is that you're trying to call FB.init() before the Facebook script actually loads.
Line 94 contains this code:
window.onload=FB.init();cycleBan();
If you're trying to execute FB.init() (and also cycleBan()?) on the window's onload event, that's not going to work. What the above code does is set the value returned by FB.init() to the window.onload handler, and then calls cycleBan(). Try this instead:
window.onload = function () {
FB.init();
cycleBan();
};
Edit after reading a bit of the Facebook API docs, it looks like you're not passing an appId to FB.init(), which I think is necessary:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId:'YOUR_APP_ID', cookie:true,
status:true, xfbml:true
});
</script>
<fb:login-button>Login with Facebook</fb:login-button>
So you should change your code to use the same structure.
Edit 2 okay, so I've never used the Facebook API before - just took another look at your page and it looks like you're already using the right basic template, and I guess you're passing the appId as a URL parameter. Oh well, shows how much I know.

On Firefox you can use the Firebug add-on (I'm guessing you know about it as you used the name in your question). Just go to the page, click the Firebug icon in the status bar at the bottom, and use the Scripts tab to go to your script code, set breakpoints, and single-step through.
You can also do this with the dev tools built into Chrome, Safari, Opera, and even IE from IE8 onward. (In earlier versions of IE you can use the free edition of VS.Net for debugging.)
One nice thing about all of these is that you can right-click an element (like your button) and choose "Inspect element" to go straight to information about it. On Chrome at least (and probably others) that includes event handlers assigned to it, which makes it easy to find things.

Make sure the script connecting to the js is secure
http://connect.facebook.net/en_US/all.js
should be
https://connect.facebook.net/en_US/all.js

If you pass the non existing FB app key to init() then only you get the error of 'FB.login() called before calling FB.init()'
Make sure, you haven't been doing the same.

Related

How can I run code after webpage has loaded in JS (window.onload is failing me)?

Heyo,
I'm trying to create a script that opens a URL and sign in using the given credentials.
Therefore I created this:
window.open("https://stackoverflow.com/users/login");
document.getElementById('email').value = "ThisIsMy#Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
But then I changed the code to wait for the page to load using window.onload:
window.open("https://stackoverflow.com/users/login");
window.onload = function() {
document.getElementById('email').value = "ThisIsMy#Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
}
However, this does not seem to work.
Therefore I added some console.log into my code to debug, like this:
console.log("starting")
window.open("https://stackoverflow.com/users/login");
console.log("page open")
window.onload = function() {
console.log("page loaded")
document.getElementById('email').value = "ThisIsMy#Email.com";
document.getElementById('password').value = "ThisIsMyPassword";
document.getElementById('submit-button').click();
console.log("signed in")
}
When I run the code in the console (Chrome/Firefox), I get back started and page open, but nothing else.
When I test the function isolated (i.e. the 3 different document.getElementById) it works just fine. Something must be wrong with the window.onload call?
From other sources here on StackOverflow I tried to use document.onload instead, and I also tried to use document.addEventListener('DOMContentLoaded', function() {...}, but none of these seems to be working either.
Does anyone have any suggestions?
#newbie
You simply can't access a cross origin page. What you are trying is only available to browser addons. And addons also require a specific permission granted by the user. For example the chrome permission to modify a webRequest: https://developer.chrome.com/docs/extensions/reference/webRequest/
window.open() returns the child window and this can be accessed IF it is about:blank or if the same-origin-rule applies (protocol, hostname and port - see pic below). Take a look at this fiddle it shows something similar to what you are trying. (CORS 1)
Here you can see which child windows you may have access to. This means modify it on the fly or override it's content/location completly.
The only method to communicate between two pages is: window.postMessage() and the window: Message-Event which provides an easy to use API for communication.
in your html page, in the script tag, where you call to your js page, add defer. like this:
<script src="your_script.js" defer></script>
I would like to remind you it is not a very good idea to use password credentials inside javascript since it is hard to protect from public appearance.
I believe you can solve this kind of problem with programs such as Python, C++ , maybe Java , but Javascript is a Client-Side program which has some limitations but if you ask me these limitations actually makes it quite fun to use most of the time.

Send a message from Dialog box (mean-stack site) to the task pane

I am trying to use Dialog API of Office addin.
I can successfully open a Dialog box from my task pane by:
$scope.openDialog = function () {
Office.context.ui.displayDialogAsync('https://localhost:3000/home',
function (asyncResult) {
dialog = asyncResult.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
});
}
My Dialog box is a mean-stack site. I have added <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script> in the index.html. And I tried to use Office.context.ui.messageParent(true);, it shows an error in console:
And I see in the doc that I don't understand quite well:
The Office JavaScript library is loaded in the page. (Like any page
that uses the Office JavaScript library, script for the page must
assign a method to the Office.initialize property, although it can be
an empty method. For details, see Initializing your add-in.)
I also tried to add Office.initialize = function () { }; in index.html, the error is still there, and processMessage of the task pane does not seem to receive anything.
So is there anything special I should do to my mean-stack site so that it could use messagePerent?
The console error will not introduce any bad effect to the dialog. We already fixed it internal. You can just ignore this error. Did you check whether office.context.ui.messageParent is null or undefined ? if it is not, then the dialog has been initialized successfully. Then it will be only something wrong with the postMessage method, what system and browser version are you using ?
1. If it is Win10 and latest version of IE, please make sure the dialog first page domain is same with the taskpane domain. Or you can use other browser to try it.
2. If it is Win7&8&8.1 and IE, then you can just try in other browser to see whether the messageParent api is work. We have already done a code change to fix the IE issue. It will be deployed to prod soon.

Unable to load script from another server - Content Security Policy issue?

I have been trying to turn a bookmarklet into a small development environment that I can use for testing some javascript and sending commands easily on the fly and updating the code on my server quickly to see the result. This has half way worked using method's I have found in this site and google however it doesn't seem to work very well and sometimes randomly doesn't work. The end goal is to have a bookmarklet that I can click on from any page and it loads a javascript file I have saved on my server. I have created the following two bookmarklets to try and get this working:
Failed Method 1:
javascript:
var s = document.createElement('script');
s.type='text/javascript';
document.body.appendChild(s);
s.src='//smewth.com/test.js';
void(0);
Method 1 in one line bookmarklet form: javascript: var s = document.createElement('script'); s.type='text/javascript'; document.body.appendChild(s); s.src='//smewth.com/test.js'; void(0);
Failed Method 2:
javascript:(
function(){
var imported = document.createElement('script');
imported.type='text/javascript';
imported.src = 'https://smewth.com/test.js';
document.head.appendChild(imported);
})();
Method 2 in one line bookmarklet form: javascript:( function(){ var imported = document.createElement('script'); imported.type='text/javascript'; imported.src = 'https://smewth.com/test.js'; document.head.appendChild(imported); })();
I got method 1 by decomposing the kickass bookmarklet from (http://kickassapp.com/). The actual one I got from their site works fine on my browser no problems. I even did a direct substitution from the URL they were using to load with my URL. The second method I found while searching on this site and this actually worked for a small while and stopped working for some unknown reason (maybe different browsers). I tried appending this script object to the head and the body on each of them with no improved results.
I created the test.js script just for this post and it contains a simple alert box statement:
$$ [/]# cat test.js
alert("hi");
$$ [/]#
NOTE: When I do this with the code embedded within the the bookmarklet itself without appending it to a head/body object then it works fine such as this:
javascript:%20alert("hi");
I did notice that with both of these methods, the code is actually getting injected into the page however I am not seeing the code is ever executed when I click the bookmark. Does anyone know which method is the best or something similar to do this so I can have javascript load through a page which I update on a remote server (reliably)? Maybe I need to attach the to a different object?
Thank you for your help.
-Jeff
UPDATE: I am showing this works while this site is loaded but it doesn't work when your at a site like google.com. Not sure what the difference is or how to accomodate this, google.com has a head and a body object too. I am showing this works in some sites and in some it doesn't.
I figured this out. There were two things occurring which accounts for the intermittent symptom of this issue. The first issue was that the site which was hosting the code was on a self-signed certificate. I began to notice the issue was occurring only when trying to run this from within secure sites. Then in Chrome I saw a error show up in the console. It would be nice if Firefox gave me a error on the console or something as this was the root of the issue. The second thing I had to do was disable OCSP in Firefox as I used a free certificate for testing purposes.
I also had to use method 1 as described above. Firefox and Chrome both did not like the anonymous function call for some reason. From now on I will refer to Chrome to look for errors in the console as Firefox has proven itself not very useful for this.

Links that don't pass referrer

I want to create a list of links opening the targets in new tabs from my private page and I don't want the referring URL to be passed on.
I tried the following method, but it didn't solve the problem:
<script>
function op(url){
window.open(url.replace(/<(?:.|\n)*?>/gm,''),'_newtab');
}
</script>
<span onclick="javascript:op(this.innerHTML);">http://www.google.com<span>
Is there any way how to spoof or blank the referrer? In the worst case I might create an iframe and put the page with links on some free hosting, but I'd prefer some more elegant solution. The only requirements are tha t it should work in Chrome, Opera, IE and FF (2011+ versions), accessibility is not an issue, since it'll be used by very few users I know.
The referring URL is part of the HTTP protocol, not the mark-up. You can't change this.
Also, you never need to specify javascript: in an event handler. It's always is and can only be javascript.
There is a rel="noreferrer" which is not yet suported by Firefox...
See also https://stackoverflow.com/a/8957778/22470
Create a tiny app on Heroku that receives a URL then forwards the user.
You could redirect to an intermediate page that redirects to the final website, this would hide the true referer.
It seems the easiest is the iframe dirty way.

Creating a tweet button without opening a new window

I'm looking to add a "tweet this" button to a site. Simple enough, right? The catch is that the site is meant to run on an embedded platform that doesn't particularly handle popup windows, so I'm trying to do everything inside the page.
I'm able to successfully create my tweet button, attach an onClick handler to it, and construct a proper twitter.com/share URL for the relevant content. All works fine when I open that URL in a new window with window.open. However, if I try to open the URL in an iframe, nothing loads inside the frame. Even loading http://twitter.com into the iframe fails in the same way. However, loading Google or any other website seems to work just fine.
Any thoughts on what I'm missing here? Thanks! --zach
Edit:
Yep, they are detecting the iframe on load and blanking the page:
if (window.top !== window.self) {
document.write = "";
window.top.location = window.self.location;
setTimeout(function(){ document.body.innerHTML='';},1);
window.self.onload=function(evt){document.body.innerHTML='';};
}
Any reasonable way to get around this, or am I stuck writing my own auth pipeline through oauth? I don't need anything from their API, just letting users tweet to their own accounts.
Twitter (like Stack Overflow) is probably using some Javascript to ensure they're not being presented in an iFrame:
if(top!=self){
//hates you
}
I ran into something similar recently, and ended up re-doing part of my app without the iFrame element.
Go and get a developper account on twitter and things are made easy for you :)
Can you simply redirect the the twitter share URL? I'm guessing they want to be careful about opening the window in iframe's to prevent malicious sites from tweeting in a user's account without giving the user a chance to first confirm their intent to send this tweet.
You said window.open worked fine for popping up the url in a new window but have you tried popping it into the parent frame?
twtWindow=window.open([url],'_parent',[specs])
#yuval Unfortunately for you, the twitter url goes to a page that has the X-FRAME-OPTIONS:SAMEORIGIN header set in the response. It's not a Javascript check. The browser will simply refuse to render the page after seeing the header. This is done to prevent a clickjacking attack, usually done to steal a user's password.
So your only other option is really to redirect your current page with window.location.href=url.

Categories