Client server javascript communication - javascript

I want to create 2 scripts, 1 for client 1 for server side.
I found snippet which allows call asyncrhonously js
<html>
<head>
</head>
<body>
<script>
(function() {
var projectId = "script";
var protocol = ('https:' == document.location.protocol ?
'https://' : 'http://');
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = protocol + 'localhost/wp/' +
projectId + '.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
})();
function optimizelyTimeout() {
window.optimizely = window.optimizely|| [];
if (!window.optimizely.data) {
window.optimizely.push("timeout");
}
}
setTimeout(optimizelyTimeout, 1000);
</script>
</body>
</html>
This produces below code:
<script type="text/javascript" async="" src="http://localhost/wp/script.js"></script>
Now I would like script.js to return some custom js code which will be injected into original webpage. I tried with:
-return("code");
-response.write("code");
but non of that worked for me.
How script.js should look like in order to return some custom js code to be executed on client side?
How can I pass arguments from client to server side call?

How script.js should look like in order to return some custom js code
to be executed on client side?
if the javascript code returned by script tag has to be invoked immediately then you need to return a self invoking function
(function(){
/* code that you want to invoke immediately after the script has been loaded*/
})(this);
How can I pass arguments from client to server side call?
just push the parameters in the script src itself
scriptTag.src = protocol + 'localhost/wp/' + projectId + '.js?param1=value';
and intercept the same on your server side

Related

Geoplugin SSL - Country undefined error

I am trying to disable my live chat from displaying by blocking countries India and Pakistan.
I used the tool from http://www.geoplugin.com and it worked great. However - I was using the typical http javascript. I just bought the SSL version from them so that there wouldn't be a conflict with my current website which uses HTTPS and the new javascript.
However - now that I use it - I get the error message
Uncaught ReferenceError: geoplugin_countryCode is not defined
My website is https://www.blueskychat.com
The code is as follows:
<script language="JavaScript" src="https://ssl.geoplugin.net/json.gp?k=..." type="text/javascript"></script>
<script type="text/javascript">
var countryCode = geoplugin_countryCode();
if (countryCode != 'IN' && countryCode != 'PK') {
window.__lc = window.__lc || {};
window.__lc.license = 8653536;
window.__lc.chat_between_groups = false;
window.__lc.ga_version = "ga";
(function() {
var lc = document.createElement('script');
lc.type = 'text/javascript';
lc.async = true;
lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(lc, s);
})();
}
</script>
Any ideas as to what is the problem and how to resolve?
Thanks!!
You're loading json response, but attempting to use javascript method.
Just replace json.gp with javascript.gp in your src attribute of loading script and it will work.

Google login / Third party authentication provider

I'm developing an angularjs app where Google login is one of it's features.
I'm using this link to implement the feature
https://blog.codecentric.de/en/2014/06/angularjs-google-sign-integration/.
Here is also the script called when the page is loaded
`
<script type="text/javascript">
(function () {
var p = document.createElement('script');
p.type = 'text/javascript';
p.async = true;
p.src = 'https://apis.google.com/js/platform.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(p, s);
})();
</script>
`
Is this the right way and how I can fetch data from google and show the data to the user and if he is happy to press sign up and then to be signed. I already have my app created into the google api service and tried many options but no success so far.
Thanks in advice.
Well this has a problem you would be login in directly with out being clicked so that might be a problem in future
Try something like this
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
In the view
function login()
{
var myParams = {
'clientid' : 'YOUR_CLIENT_ID.apps.googleusercontent.com', //You need to set client id
'cookiepolicy' : 'single_host_origin',
'callback' : 'loginCallback', //callback function
'approvalprompt':'force',
'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
};
gapi.auth.signIn(myParams);
}
Convert this codes to Angular .
Please see this question for details

How to send response with javascript to draw html elements

I'm creating a script like twitter in which user just provide an id and all his/her tweets get loaded on site where the script inserted.
What I've done is
User should copy this code to load my widget
<a class="getStarted" data-getStartedID="123456789">Get Started App ID</a>
<script>
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+"://localhost/practices/js_practice/siteOpen.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","getStarted-C");
My siteOpen.js is as below :
!function(d){
var a = d.getElementsByClassName('getStarted');
var x = document.getElementsByClassName("getStarted")[0].getAttribute("data-getStartedID");
var r = new XMLHttpRequest();
var appID = x;
r.open("POST", "openwebIndex.php", true);
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", appID.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
if(r.responseText.trim()==1){
return '<p>output to be draw on where script is pasted</p>';
if(console)console.info('Valid appID');
}
};
r.send('appID='+appID);
}(document);
i don't know what to do to send the response and load/draw my widget on user's website.
My response will be in html elements.
Please suggest me what should i do. I just stuck at this point.
EDIT
I'm getting object HTMLScriptElement when I alert js variable.
Just trying adding the html code in the body tag.
users html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script src="widget.js"></script>
Your widget.js
// var appId = d.getElementsByClassName('getStarted');
// process the app id and make the output here
var output = "<div>This is the content of the widget</div>";
document.body.innerHTML += output;
This will show the content in the users html file. If you have cross domain issue, use JSONP for resolving that.

Injecting javascript dynamically and using it

I also create a javascript file dynamically that uses those variables:
function callbackF(data){
console.log(data.script);
document.getElementsByTagName('head')[0].innerHTML=data.script;
var script = document.createElement("script");
script.setAttribute("src", "http://widget.example.com/sprk.1.0.2.js");
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "grazit_script");
document.getElementsByTagName('head')[0].appendChild(script);
}
This is what i get in my head:
This is what is printed to the console log:
<script type='text/javascript'>var dbnwid=16476; var dbnpid=23369; var dbnwebid=19720; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>
and then the script:
<script src="http://widget.example.com/sprk.1.0.2.js" type="text/javascript" id="grazit_script"></script>
The second script should get the variables that are in the second script..but it doesnt..then it complains about why it doesnt get those variables
UPDATE:
Both of those ways below didnt work for me:
eval(data.script);
var ss= new Function(data.script)();
Because scripts run when they are loaded. Adding a script tag using innerHTML doesn't run the code inside the tag.

NowJS error! I can't get the example to work!

I was following along the tutorial at http://nowjs.com/doc when I encountered some errors.
<html>
<head>
<title>index.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
<script src="http://localhost:8080/NowJS/now.js"></script>
<script>
$(document).ready(function(){
var name = prompt("what is your name?","");
now.receiveMessage = function(name,message){
alert(name+" "+message);
};
$('.butt').click(function(){
alert($('#put').val());
now.distributeMessage(name,$('#put').val());
$('#put').val('');
});
});
</script>
and for the server:
var fs = require('fs');
var sys = require('sys');
var server = require('http').createServer(function(req,response){
fs.readFile('index.html',function(err,data){
response.writeHead(200);
response.write(data);
response.end();
});
});
server.listen(8080);
sys.print('woot');
var everyone = require('now').initialize(server);
everyone.now.distributeMessage = function(name, message){
sys.print(name+" "+message);
everyone.now.receiveMessage(name,message);
};
I highly suspect it has something to do with my tag since there isnt anything at /NowJS/now.js.
Can someone enlighten me on this part:
On pages that you would like to use NowJS on, simply include this script tag in your HTML head: NowJS only works on pages that are served through the same http server instance that was passed into the initialize function above.
Thanks for your time.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
script tags can't be self-closed.
In the docs the path in the script tag is lower-case, /nowjs/now.js, whereas in your snippet it is /NowJS/now.js, and so I guess this is the reason it doesn't work.

Categories

Resources