Google App Scripts : Javascript code inside the HTML file not functioning - google-apps-script

I have been trying to write a small Google App Script which has the Google+ badge as shown here. For this I have a plain HTML file where I have included the HTML as shown on that page. The HTML page is as follows :
<html>
<body>
<div class="g-plus" data-href="{Page-Link}" data-rel="publisher"></div>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
alert("Added Badge!");
})();
</script>
</body>
</html>
The result is a blank page. There is no badge added to the page . I assume this is because the javascript function is not being run( I added an alert and there wasnt any pop-up ).I am not able to figure out why the function is not being run.
Any help is appreciated.

Unfortunately I'm not too experienced with Javascript so I'm guessing here. I've programmed in coffeescript a while ago and its compiler automatically wraps the generated code in an anonimous function just as in your code. This function is called so:
(function() {//...}).call(this);
Maybe this works.
Alternatively you might want to move the alert test above the badge generation. This would show if the javascript is run at all. Maybe the error lies in your badge creation code.
My final idea would be to name your function and register it as a callback on body.onload . It's always a good idea to let the browser load the page before accessing the dom

Related

URL changes but will not refresh the page

I use a software called Bookee and they run our scheduling features. Right now the website has submenus and when you click the one it will change the url but not refresh the page. I do not know anything about coding and was told the issue was in this code. How do I fix it and can anyone explain why the url changes but doesn't refresh the page.
Here is a link to the code in the elementor system within Wordpress. https://d.pr/i/3dzf4e
<div id="studioyou-embed"></div>
<script>
const date = Date.now();
const xscript = document.createElement("script");
xscript.setAttribute("src",https://graysanatomyacademy.onbookee.com/embed/index.js?t=${date});
const embedContainer = document.querySelector("body");
xscript.onload = function () {new StudioYouEmbed('graysanatomyacademy.onbookee.com');};
embedContainer.appendChild(xscript);
ayo pretty sure it's cause you never ended the script with a Im not sure if this is all your code tho. This is a fixed version.
<div id="studioyou-embed"></div>
<script>
const date = Date.now();
const xscript = document.createElement("script");
</script>
how did you do this without coding knowledge lol

use an include to include an html file that contains a script

I am working on a Google Apps Script. My situation is that I have an index.html file and a few others which should all share a menu on the side.
I therefore have a function as follows
function include(File) {
return HtmlService.createHtmlOutputFromFile(File).getContent();
};
and use
<?!= include('leftMenu'); ?>
to include that in my html files.
The problem I have is that in the included file there is a function called that is defined in my Code.gs
<div class="leftmenu">
Main menu<br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=newInvoice'>New invoice</a><br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=index'>Home</a>
</div>
This function works as I would expect as long as these lines are in the "main" html file but they produce text if they are in the "included" html file.
I hope that makes sense and some one is kind enough to explain what the problem is and hopefully how I can get round it.
Thank you
Neill
14 Dec. 2016 edited to try and explain exactly what my problem is
I have a html file named “newinvoice.html”.
This has javascript functions in it as follows
<script type="text/javascript">
function formSubmit() {
google.script.run.withSuccessHandler(updateUrl).onSubmitButton(document.forms[0]);
}
function updateUrl(url) {
var successMsg = document.getElementById('output');
successMsg.innerHTML = 'New invoice created, saved and sent per Email';
}
</script>
I can move these functions into a separate html file as you suggested. This is called menu_JS.html and is included in my main file with
This works perfectly.
I have a call to one of these these functions - also in the main html “newinvoice.html” This is as follows
<div class="leftmenu">
Main menu<br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=newInvoice'>New invoice</a><br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=index'>Home</a>
</div>
If I move this into a separate file “leftMenu.html” and include that in “newinvoce.html” with
Then the output no longer works.
It appears that the scripts are trying to run before the files are included instead of the include and then the execution as I am used to from PHP.
As always, I appreciate anyone willing to take the time to help me. This is frustrating. Thank you!
Create another HTML file and put the script you want to run client side in that file. Then use the same include statement to include that file.
So make menu_JS.html and place your functions in that, between script tags:
<script>
firstFunction(){
alert("In the first function");
}
secondFunction(){
alert("In the second function");
}
</script>
And in your main HTML template file, preferable after the body loads, place:
<?!= include('menu_JS'); ?>
NOTE that the script is in an HTML file and NOT a Script file.
EDIT: Nov 15 2016
Below is the variation of the function which I have that is working for my needs. Note that I am evaluating the included html file. I had previously used code more similar to your (commented out) and changed it to this some time ago:
function include(filename) {
// return HtmlService.createHtmlOutputFromFile(filename)
return HtmlService.createTemplateFromFile(filename).evaluate()
.getContent();
}
//function includeRaw(filename) {
// return HtmlService.createTemplateFromFile(filename).getRawContent();
//}
And this is how I load the initial html file. This is often in the doGet() function, but may be elsewhere
var result=HtmlService.createTemplateFromFile('GridView').evaluate()
.setTitle('Boxwood Registrations')
.setWidth(1285)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return result;

HREF with https link in a frame doesn't work [duplicate]

I am trying to put google.com into an iframe on my website, this works with many other websites including yahoo. But it does not work with google as it just shows a blank iframe. Why does it not render? Are there any tricks to do that?
I have tried it in an usual way to show a website in an iframe like this:
<iframe name="I1" id="if1" width="100%"
height="254" style="visibility:visible"
src="http://www.google.com"></iframe>
The google.com page does not render in the iframe, it's just blank. What is going on?
The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.
See: Mozilla Developer Network - The X-Frame-Options response header
IT IS NOT IMPOSSIBLE.
Use a reverse proxy server to handle the Different-Origin-Problem. I used to using Nginx with proxy_pass to change the url of page. you can have a try.
Another way is to write a simple proxy page runs on server by yourself, just request from Google and output the result to the client.
As it has been outlined here, because Google is sending an "X-Frame-Options: SAMEORIGIN" response header you cannot simply set the src to "http://www.google.com" in a iframe.
If you want to embed Google into an iframe you can do what sudopeople suggested in a comment above and use a Google custom search link like the following. This worked great for me (left 'q=' blank to start with blank search).
<iframe id="if1" width="100%" height="254" style="visibility:visible" src="http://www.google.com/custom?q=&btnG=Search"></iframe>
EDIT:
This answer no longer works. For information, and instructions on how to replace an iframe search with a google custom search element check out:
https://support.google.com/customsearch/answer/2641279
You can use https://www.google.com/search?igu=1 instead of https://google.com/ , it works. This issue is it has X-Frame-Options Header policy and browsers follow those policies.
You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.
The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.
google.php
<script>
(function() {
var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>
yourpage.php
<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>
You can bypass X-Frame-Options in an using YQL.
var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
else if (data && data.error && data.error.description) loadHTML(data.error.description);
else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
url = src;
var script = document.createElement('script');
script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
document.body.appendChild(script);
};
var loadHTML = function (html) {
iframe.src = 'about:blank';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
iframe.contentWindow.document.close();
}
loadURL(iframe.src);
<iframe src="http://www.google.co.in" width="500" height="300"></iframe>
Run it here: http://jsfiddle.net/2gou4yen/
Code from here: How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?
If you are using PHP you can use file_get_contents() to print the content:
<?php
$page = file_get_contents('https://www.google.com');
echo $page;
?>
This will print whatever content file_get_contents() function gets in this url.
Please note that since you are displaying content as string instead as a actual web page, things like relative path images are not shown correctly, because /img/myimg.jpg is now loading from your server and not from google.com anymore.
However, you can play with some tricks like str_replace() function to replace absolute urls in images:
<?php
$page = file_get_contents('https://www.google.com');
echo str_replace('src="img/','src="https://google.com/img/',$page);
?>
This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.
<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">
web
I guess the better option is to just use Curl or similar.
Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

How to configure my HTML to use i18next?

I have an application with nodejs, express and HTML on client side. I'd like to internalize my project using i18next. On nodejs side, it's ok, I required i18next and started it.
var i18n = require('i18next'),
app = express();
i18n.registerAppHelper(app);
i18n.init({lng: "en-US"}, function(t){
var trad = i18n.t("trad.key1");
console.log("trad = " + trad);
});
In console log, I have the traduction of translation.json to variable trad.key1. It is correct.
Know, the question: what I need to do to use i18next on client side, HTML page? I found some examples to do this, but using jQuery, and I don't use that.
Thanks for help.
It's done.
On HTML file, I needed to reference i18next.js and init i18n, like below. On init i18n, I specified the correct translation.json, as can you see.
<script type="text/javascript" src="i18next/i18next.js"></script>
<script>
window.onload = function() {
i18n.init({
lng: "en-US",
resGetPath:"locales/__lng__/translation.json"
},function(t) {
var translate = i18n.t("var.key1");
});
};
</script>
That's all.

Controlling Soundcloud HTML5 Widget Player Volume

I have been attempting to use the example given on a Soundcloud Blog page so I can set the volume lower.
I only changed the iframe size and src= to my playlist and set volume to 10 so I could notice the difference if it worked. So far I observe no change, volume is still at 100%.
I have tried it with and without placing the following in the head of my template. It doesn't seem to matter.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Here is the code that I adjusted from the Soundcloud example:
<iframe id="sc-widget" width="350" height="332" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F1417174&auto_play=true&show_artwork=false&color=37415f"></iframe>
<script src="http://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<script type="text/javascript">
(function(){
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.PLAY, function() {
// get information about currently playing sound
widget.getCurrentSound(function(currentSound) {
console.log('sound ' + currentSound.get('') + 'began to play');
});
});
// get current level of volume
widget.getVolume(function(volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(10);
});
}());
</script>
This code is live on a Joomla site.
Can someone please help me understand what I'm lacking to control the volume?
Is it a jquery conflict? If so, any thoughts on how to resolve it?
the volume range is actually from 0 to 1, this is stated wrongly in the documentation. So if you would like to set the volume to 10%, you would need this:
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.setVolume(0.1);
The previous answer is no longer accurate. The setVolume() api has been fixed/changed to take in an int between 0 and 100.
I stumbled upon this question trying to quickly change the volume of an embedded SoundCloud iframe using the chrome console. I created a quick gist for myself.
https://gist.github.com/propagated/78aaedfbc0c23add7691bb975b51a3ff
//load soundcloud js api if needed
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://w.soundcloud.com/player/api.js';
document.head.appendChild(script);
//get the id of the player iframe or inject it using chrome
var id = 'scplayer',
widgetIframe = document.getElementById(id),
fixWidget = SC.Widget(widgetIframe);
fixWidget.setVolume(50); //% between 1 and 100