I have a bit of embed code that I need to place on a Google Site, this site will be restricted to our Google domain members. I can place this JavaScript in a Google Gadget and it works fine.
<script type="text/javascript" src='https://HOSTNAME/Forms/js/forms-embed.js?v=9.2'>
</script>
<script type="text/javascript">
var lfembed = new LaserficheForms.Form(null /*element to place form in*/,{bpid: '1', host:'https://HOSTNAME/Forms', params:PARAMS, autoheight: false}).getFrm();
lfembed.style.height = "100%";
</script>
The problem is that I want to be able to get the currently logged in user's email address and pass that in the params: section of the code above.
From what I can tell, you can't do this within a Google Gadget. I can retrieve the current email address with the Google Apps Script object below, but I don't know how to make the two work together.
function doGet() {
var gauser = Session.getActiveUser().getEmail();
var output = ContentService.createTextOutput(gauser);
return output;
}
Another problem is that Google sanitizes some of the JavaScript when I try to include all of the code in just the Google Apps Script.
I really don't have much experience in this area, so if anyone could point me in the right direction I'd appreciate it.
I learned about JSONP today.
I ended up getting this to work by publishing the following Google Apps Script web app.
function doGet(request) {
var gauser = Session.getActiveUser().getEmail();
return ContentService.createTextOutput(
request.parameters.prefix + '(' + JSON.stringify(gauser) + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
Then I called the web app service via URL in my XML Gadget
<script src="https://WEBAPPURL?prefix=lfdo"></script>
This placed the username value into the lfdo function, which I inserted into the parameter string I needed it in.
The full Content section of the XML gadget:
<![CDATA[
<script type="text/javascript" src='https://HOSTNAME/Forms/js/forms-embed.js?v=9.2'></script>
<script type="text/javascript">
function lfdo(gauser) {
console.log(gauser);
var lfembed = new LaserficheForms.Form(null /*element to place form in*/,{bpid: '1', host:'https://HOSTNAME/Forms', params:'Name='+ gauser, autoheight: false}).getFrm();
lfembed.style.height = "100%";
gadgets.window.adjustHeight();
}
</script>
<script src="https://WEBAPPURL?prefix=lfdo"></script>
]]>
This article on Google Developers set me in the right direction.
This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:
page.html:
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('mypage.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('mypage.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<div id="load_tweets"> </div>
</body>
</html>
If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:
http://37.187.90.121:3874/currentsong?sid=1&c=
The output of this source is like this:
Inna - Un Momento
If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?
EDIT1:
ok is a policy problem, how i can resolve it?
EDIT2:+
The proxy php page solution don't work.
I have make this php page:
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>
But i have this error message:
Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Edit3:
The external service give me a javascript to get the information:
window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('<span title="'+r+'">Unavailable</span>'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++<this.settings.poll_limit)&&setTimeout(this.poll_all,this.settings.poll_frequency)},poll_all:function(){window.centovacast.streaminfo._poll_all()},register:function(e,t,n,r){this.registry[t]||(this.registry[t]={charset:n,mountpoint:r,current_song:"",id:{}});var i=e.match(/^cc_strinfo_([a-z]+)_/);i&&(this.registry[t].id[i[1]]=e)},load:function(){var t=e(this).attr("id");if(typeof t!="string")return;var n=t.replace(/^cc_strinfo_[a-z]+_/,""),r="",i="",s=/_cs-([A-Za-z0-9\-]+)$/,o=s.exec(n);o&&(r=o[1],n=n.replace(s,"")),s=/_mp-([A-Za-z0-9\-]+)$/,o=s.exec(n),o&&(i=o[1],n=n.replace(s,"")),window.centovacast.streaminfo.register(t,n,r,i)},run:function(){e(".cc_streaminfo").each(window.centovacast.streaminfo.load),window.centovacast.streaminfo.poll_all()}}});
You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js
Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.
This script give me an output like:
"Radio Name - Author - Title of song"
and this is a link (if you click on it open another page).
I need to get only "Author - Title of song" with no link. Any idea?
Edit4:
I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var div = document.getElementsByClassName('cc_streaminfo')[0];
document.write("w1" + document.getElementsByClassName('cc_streaminfo')[0]);
document.write("w2" + document.getElementsByClassName('cc_streaminfo')[1]);
document.write("w3" + document.getElementsByClassName('cc_streaminfo')[2]);
var container = document.getElementById ("cc_strinfo_summary_radiowhite");
var spans = div.getElementsByTagName("span");
document.write("il mio script: " + spans[0] + "!");
document.write("il mio script: " + container + "!");
//var first_load =
function firstLoad()
{
$('#load_tweets').load('current_g.php?song=ciao');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('current_g.php?song=' + cc_streaminfo).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<br>
<span id="cc_strinfo_summary_radiowhite" class="cc_streaminfo">sss</span>
<div id="load_tweets"> </div>
</body>
</html>
I think this has something to do with CORS. Basically, unless the webpage at 37.187.90.121 explicitly states that it trusts the sources of the domain under which your website is running, your browser will not make the request.
If you are the owner of 37.187.90.121, you can add custom headers to allow inclusion of your response in other webpages.
Check your javascript console of your browser to get more details.
Using jQuery to get (.load()) the contents from a div on another page ( same domain ) to add to a div on the current page is like :
$("#dividoncurrentpage").load("/otherpage.php #dividonotherpage");
Is this what you need ?
It's because:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
mstaessen has explained on the post above.
The alternative solution is: You can create a file called, for example song.php and add the following code.
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong?sid=1&c=");
?>
And update the script to
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('song.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('song.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
Its better to use jQuery $.ajax to get the content. Link
By using $.ajax you have many ways to work around this issue like crossDomain or get the result in Json format by setting the dataType that you will receive from the server to JSON or JSONP
I have a page called main.jsp which is in domain domain1 and it has a iframe which loads contents from domain2. Basically main.jsp is a common contents and in iframe we load contents from other web applications deployed on different servers.
My problem is I want to refresh the content inside iframe automatically (say 5 seconds). I tried this code first:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />" />
Err: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame
I tried this code:
<script type="text/javascript">
window.setTimeout(function(){ window.location.reload() }, 15000);
</script>
Which also gives me same error. Can anyone guide me how to achieve this?
Note:
I have added this code to get rid of cross-domain issue:
<script type="text/javascript">
document.domain = window.location.hostname.replace('www.', '');
</script>
Try adding it dynamicaly
function addRefresh(){
var meta = document.createElement('meta');
meta.setAttribute("http-equiv", "refresh");
meta.setAttribute("content", "5");
document.getElementsByTagName('head')[0].appendChild(meta);
}
if(location.origin === 'domain1.com'){
addRefresh();
}
I am trying to understand the same origin policy of browsers. Theoretically things seem ok. So i am now trying to practically understand it using a small demo.
I have 2 domains hosted on wamp, viz domain1.com and domain2.com
domain1.com consists of index.php, innocent.php and 2 js files in a javascript folder, namely dom1_javascript.js and dom1_normal.js
here are the details of the above files: -
index.php
<?php
$value = "domain 1 cookie";
// send a simple cookie
setcookie("Dom1Cookie",$value);
?>
<html>
<script type="text/javascript" src="../javascript/dom1_javascript.js">
</script>
<body>
this is from doamin 1
</body>
</html>
innocent.php
<?php
$userSecret=$_GET['userCreds'];
if($userSecret)
{
echo "the user's secret is "+$userSecret;
}
else
{
echo "sorry user secret not found";
}
?>
dom1_javascript.js
alert(document.cookie);
dom1_normal.js
alert("alert domain 1");
alert(document.cookie);
//referring the div
var bdy=null;
// creating the form
var secretForm=document.createElement("form");
secretForm.id="goodForm";
secretForm.method="get";
var myQryStr="http://domain1.com/innocent.php?userCreds=abcd";
alert(myQryStr);
secretForm.action=myQryStr;
//creating the text box in the form
var hiddenBox=document.createElement("input");
hiddenBox.type="text";
hiddenBox.name="secBox";
hiddenBox.value="abhinav";
//appending the box to the form
secretForm.appendChild(hiddenBox);
//appending the form to the div
bdy=document.getElementById("mydiv");
alert(bdy);
bdy.appendChild(secretForm);
//submitting the form
document.getElementById("goodForm").submit();
domain2.com consists of 2 versions of index.php, viz, index.php and index1.php
here are the details of the above php file: -
index.php
<?php
$value = "domain 2 cookie";
// send a simple cookie
setcookie("Dom2Cookie",$value);
?>
<html>
<head>
<script type="text/javascript" src="http://domain1.com/javascript/dom1_javascript.js">
</script>
</head>
<body>
<div id="mydiv">
<img src="http://domain1.com/images/dom1.bmp"/>
this is from doamin 2
</div>
</body>
</html>
index1.php
<?php
$value = "domain 2 cookie";
// send a simple cookie
setcookie("Dom2Cookie",$value);
?>
<html>
<head>
<script type="text/javascript" src="http://domain1.com/javascript/dom1_normal.js">
</script>
</head>
<body>
<div id="mydiv">
<img src="http://domain1.com/images/dom1.bmp"/>
this is from doamin 2
</div>
</body>
</html>
I am using firefox as the browser to test these scritps.
First I goto domain1.com in the browser. This sets the domain1 cookie. Then I goto domain2.com/index.php
As expected, the script on domain2/index.php sets the domain2 cookie. Then the javascript from domain1 gets loaded which says
alert(document.cookie)
The execution of this script alerts the domain2 cookie value.
Assumption1: -
So my understanding here is that due to the same origin policy of the browser, even though the script was called from domain1, it did not alert the domain1 cookie, but instead alerted the domain2 cookie.
Please let me know if I am correct in the above assumption ?
Now I clear the browser cache and remove all the cookies from the browser. Run domain1.com again, which again sets domain1 cookie. And then, this time I goto domain2.com/index1.php which sets the cookie for domain2 and then accesses the script present in
domain1.com/javascript/dom1_normal.js
Now if my assumption1 was correct,( i.e. a javascript from domain1.com when imported in domain2.com will get executed with reference to domain2 only, and not its incoming domain, as per the same origin policy) then in this case also it should be the same with dom1_normal.js. So the javascript in dom1_normal.js should have access to all the HTML elements in domain2/index1.php It does not really so happen as confirmed by
bdy=document.getElementById("mydiv");
alert(bdy);
in domain1.com/javascript/dom1_normal.js which alerts null
please let me know where am i going wrong. And i have gone through more than a dozen discussions (on stack overflow and elsewhere including MDN, wiki, google etc.) and articles about same origin policy, but none of it has made the idea clear to me.
The Same-Origin policy doesn't have much to do with loading JavaScript. Regardless of where a script comes from, its actions take place under the aegis domain of the main page. Thus, if your main page comes from "domain1", then all scripts execute in the context of "domain1", whether they came from that domain or any other domain.
Note that it's not possible to access the source code of a script that loads from some other domain.
The reason your "dom1_normal" script reports "null" for that element reference is probably because you're importing the script before the <body>. The DOM is built incrementally, but scripts run synchronously when they're loaded, so if you call getElementById() for some element that's after the <script> tag, it won't be there.
We try to display the google ad in an iframe that we add dynamically. In an iframe, the field "src" is generally an url, but we want to use the data:text/html format to be able to use directly our ad code. It works for simple JavaScript code like a document.write('hello world')<\script>, but not with the google ad code.
We simulate this in an html file :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function resizeFrame(f) {
f.style.height = 60 + "px";
}
$(document).ready(function() {;
var htmlCode = document.createElement("div");
var head = document.getElementById('google_ad_468x60');
var myFrame = document.createElement("iframe")
myFrame.name = "childframe"
myFrame.id = "childframe"
myFrame.src = "data:text/html, " + "<script>" + "<!--\ngoogle_ad_client = \"pub-0123456789abcdef\";\ngoogle_alternate_color = \"FFFFFF\";\ngoogle_ad_width = 468;\ngoogle_ad_height = 60;\ngoogle_ad_format = \"468x60_as\";\ngoogle_ad_channel =\"0123456789\";\ngoogle_color_border = \"FFFFC6\";\ngoogle_color_bg = \"FFFFFF\";\ngoogle_color_link = \"000000\";\ngoogle_color_url = \"666666\";\ngoogle_color_text = \"333333\";\n//-->"+"<\/script>"+ "<script src = \"http://pagead2.googlesyndication.com/pagead/show_ads.js\">"+"<\/script>"
myFrame.width = "468"
myFrame.scrolling = "no"
myFrame.setAttribute('marginheight', '0px')
myFrame.setAttribute('marginwidth' , '0px')
myFrame.setAttribute('frameborder' , '0' )
head.appendChild(myFrame)
});
</script>
</head>
<body onload="resizeFrame(document.getElementById('childframe'))" bgcolor="#FFFF00">
<div>
<h1>Before Google ad</h1>
</div>
<div id="google_ad_468x60">
<-- Here is display the the Google ad --!>
</div>
<div>
<h1>After Google ad</h1>
</div>
</body>
</html>
We do not have an error with Mozilla, but with Chrome we have this error, in both case the google ad is not displayed:
Unsafe JavaScript attempt to access frame with URL oursitewiththetestfile.com from frame with URL file:///home/lucas/Bureau/google_ad.html from frame with URL data:text/html, <script>google_comments</script> <script type="text/javascript" src="google_path.js"></script>. Domains, protocols and ports must match
In Chrome's intent to keep hackers and virus creators at bay, they do not allow access to an iframe using javascript when it is communicating with a different domain then the site it is hosted on.
You are going to be stuck in this method and I am unsure that there is a workaround. Either way, Google ads should be placed directly into the website as it uses the content to generate relevant advertisements to be displayed on the page. If you are looking for a way to display your own advertisements, it should either be done dynamically, written in the code language of choice, or using the ad creator on adsense.google.com to display your own ads instead of public service ads.
I personally feel that it would be much more simple that way.
Google does not want you to put ads in a frame and will ban you if they find out... Its in the terms of service section 5...