Google Trends embed is destroying my webpage - javascript

I am doing my damnedest to embed a Google trends chart into a section of my site.
In theory, it seems easy:
1.) copy script from Google:
2.) Clear a space in your webpage:
3.) Add the code:
<div class="full-row4" style="height: 300px;">
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script>
<script type="text/javascript">
trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"/m/078rys","geo":"","time":"today 12-m"}],"category":0,"property":""},
{"exploreQuery":"q=%2Fm%2F078rys&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}
);
</script>
</div>
Seems easy right? wrong!
Every time I do this, I get this result:
Upon further inspection, I found that when those scripts were loaded in, it wipes my entire body of the webpage. (Note: the chart gets loaded in thru an AJAX call containing the entire active page minus the navbars)
I've tried an array of different logic to try and get this to work, but everything I try deletes all HTML in the body tag of the webpage. (script tags are still there)
I found people with a similar issue, but it seems Google has changed how you embed these widgets into a site. Rendering any previous stackoverflow documentation useless. (at least from what I found)

you can use renderExploreWidgetTo() function instead, it takes DOM element as first parameter:
var divElem = document.getElementById('wrapper');
trends.embed.renderExploreWidgetTo(divElem,"TIMESERIES", {"comparisonItem":[{"keyword":"dbs bank","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dbs%20bank&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"});

Google trends embed script create an iframe at the hosting website.
Here is a simple example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>hello</h1>
<div>
<script type="text/javascript" src="https://ssl.gstatic.com/trends_nrtr/1386_RC02/embed_loader.js"></script> <script type="text/javascript"> trends.embed.renderExploreWidget("TIMESERIES", {"comparisonItem":[{"keyword":"dogs","geo":"","time":"today 12-m"}],"category":0,"property":""}, {"exploreQuery":"q=dogs&date=today 12-m","guestPath":"https://trends.google.com:443/trends/embed/"}); </script>
</div>
<h1>world</h1>
</body>
</html>
As you can see, the body is not affected.
The problem is probably not with the trends scripts, but a more general issue.
Try creating an iframe at your page, does it display correctly?

Related

Wordpress: how to use javascript variables into html body

I'm really new in Wordpress, Javascript and HTML so I know this question is really basic, but I wasn't able to find it solved anywhere.
I want to create some variables in javascript and then display them in my page which is created in Wordpress.
Reading other posts I've found I need to insert a javascript code that at the end stores my variable this way (dummy version):
<script type="javascript">
document.getElementById('test').innerHTML = 'hello';
</script>
And then on the text block I want to display my variable to be displayed I should add this code:
<body>
<p id="test"></p>
</body>
However I've tried adding the javascript in the header (Tatsu header) and also tried adding it in the text block (HTML version) in different combinations and it never worked. Tried adding the script block before and after the body block, and also tried having it inside, before and after the display line.
If I try the following it works:
<body>
<p>hello</p>
</body>
So I guess my problem is that I'm not setting the variable properly.
Can anyone help? Apologies if this is already solved somewhere, spent some hours and wasn't able to find it.
Thank you in advance.
Your problem is the type of which you're using here:
<script type="javascript">
I noticed this whilst constructing an example of this problem.
javascript is not a correct mime type.
It should be text/javascript as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Please note this is not a complete list. Such as application/javascript also being valid. Please also see https://www.iana.org/assignments/media-types/media-types.xhtml
Working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="test">
This shouldn't show up
</p>
<script type="text/javascript">
console.log("####### JAVASCRIPT IS RUNNING ######")
document.getElementById('test').innerHTML = 'hello';
</script>
</body>
</html>

Is it possible to retrieve the *full* HTML page source of an iframe with Javascript?

I am trying to figure out how to retrieve the full (that means all data) HTML page source from an <iframe> whose src is from the same originating domain as the page that it is embedded on. I want the exact source code at any given time, which could be dynamic due to Javascript or php generating the <iframe> html output. This means AJAX calls like $.get() will not work for me as the page could have been modified via Javascript or generated uniquely based on the request time or mt_rand() in php. I have not been able to retrieve the exact <!DOCTYPE> declaration from my <iframe>.
I have been experimenting around and searching through Stack Overflow and have not found a solution that retrieves all of the page source including the <!DOCTYPE> declaration.
One of the answers in How do I get the entire page's HTML with jQuery? suggests that in order to retrieve the <!DOCTYPE> information, you need to construct this declaration manually, by retrieving the <iframe>'s document.doctype property and then adding all of the attributes to the <!DOCTYPE> declaration yourself. Is this really the only way to retrieve this information from the <iframe>'s HTML page source?
Here are some notable Stack Overflow posts that I have looked through and that this is not a duplicate of:
Javascript: Get current page CURRENT source
Get selected element's outer HTML
https://stackoverflow.com/questions/4612143/how-to-get-page-source-using-jquery
How do I get the entire page's HTML with jQuery?
Jquery: get all html source of a page but excluding some #ids
jQuery: Get HTML including the selector?
Here is some of my local test code that illustrates my best attempt so far, which only retrieves the data within and including the <iframe>'s <html> tag:
main.html
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var doc = document.getElementById('iframe-source').contentWindow.document;
var html = $('html', doc).clone().wrap('<p>').parent().html();
$('#output').val(html);
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="javascript:test()"></iframe>
</body>
</html>
iframe.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html class="html-tag-class">
<head class="head-tag-class">
<title>iframe Testing</title>
</head>
<body class="body-tag-class">
<h2>Testing header tag</h2>
<p>This is <strong>very</strong> exciting</p>
</body>
</html>
And here is a screenshot of these files run together in Google Chrome version 27.0.1453.110 m:
Summary
As you can see, Google Chrome's Inspect element shows that within the <iframe> the <!DOCTYPE> declaration is present, so how can I retrieve this data with the page source? This question also applies to any other declarations or other tags that are not contained within the <html> tags.
Any help or advice on retrieving this full page source code via Javascript would be greatly appreciated.
Here is a way to build it from the doctype, seems to work for html 4 and 5, I didn't test for stuff like svg.
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var d = document.getElementById('iframe-source').contentWindow.document;
var t = d.docType;
$('#output').val(
"<!DOCTYPE "+t.name+
(t.publicId? (" PUBLIC "+JSON.stringify(t.publicId)+" ") : "")+
(t.systemId? JSON.stringify(t.systemId) :"")+
">\n" + d.documentElement.outerHTML );
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="test()"></iframe>
</body>
</html>
this also uses HTML.outerHTML to make sure you get any attribs on the documentElement.

Can't import javascript code with innerHTML

I've built a webpage that is basically a main-page with a div that is filled with different pages by using AJAX. This basically works by loading pages into a div by using innerHTML. One problem I ran into was when a page with javascript is loaded into that div all of the other code runs fine; just the javascript doesnt work.
Main-page(index.php):
<html>
<head>
<script type="text/java">
////bunch of functions////
////Ends up that page_request on this instance is 'graph.php'////
document.getElementById('mydiv').innerHTML=page_request.responseText
</script>
</head>
<body>
<div id="mydiv"><div>
</body>
</html>
Child-page(loaded in div(graph.php)):
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" media="screen" />
<script src="other_stuff.js"></script>
</head>
<body>
<script>
///bunch of script////
</script>
</body>
</html>
Now when loading the page itself (opening graph.php) I notice that everything works fine; it is just when I import graph.php to index.php through innerHTML into my div it does not work (no errors just nothing is shown). I have read through many other posts and guides and did not come up with any distictive solution; thinks I have seen were:
Put eval() around my code [I saw on a guide that this could lead
to malicious user attacks].
Create the scripts on the main page then just import the data using:
document.createElement() and .parentNode.insertBefore()
Create a listener and call the functions when I open graph.php
And this good example
Even though I am not 100% sure how this example could work because I have php populate information for the javascript to collect and then make my graph on graph.php; so if I put that function into index.php the php will already be loaded so I would have to refresh the page or call them to update information somehow. Just for some context I am ok at php but I am new and struggle with javascript so I do not know what solution would fit my situation or work the best. Any tips/examples would be greatly appreciated, thank you for your time.
From you code snippets it seems you're looking to embed complete pages within the main page. If that's the case, a more straightforward approach would be to use an iframe element instead.
For example:
...
<div id="main-page-container">
<iframe src="some-path/graph.php" scrolling="no" frameborder="no"></iframe>
</div>
...
See reference and usage example.
I would suggest using jQuery's .load() function for this.
Take a look here: jQuery API
Older browsers such as IE8 and below don't allow you insert a string that contains javascript and execute it, in any form.
Take for instance:
function addScriptText(js_code) {
var element = document.createElement("script");
element.innerHTML = js_code;
document.head.appendChild(element);
}
will not work in IE8 and below.
You must use eval to accomplish this:
function addScriptText(js_code) {
window.eval.call(window, js_code);
}
Otherwise you need to dynamically request an external js file such as:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "externalScript.js";
document.getElementsByTagName("head")[0].appendChild(script);
Note: The page you are loading (page2.html in this example) must be on the same domain as the page that is loading it (page1.html in this example)
Working solution with jQuery:
Page 1:
<!DOCTYPE html>
<html>
<head>
<title>Page 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#page2").load("page2.html");
});
</script>
</head>
<body>
<h1>Page 1 Header</h1>
<div id="page2">
</div>
</body>
</html>
Page 2:
<h2>Page 2 Header</h2>
<script type="text/javascript">
alert("Page 2 loaded and javascript executed!");
</script>

Manually render dynamically generated Google 'plus one' button

Here's the scene:
The webpage doesn't have a google+ button.
User clicks a button.
AJAX request is sent which loads some text and the google+ button (<g:plusone href="http://www.website.com"></g:plusone>)
into a div.
I can see when I look at the code that it is there, but it is not rendering.
I've heard that this might be useful:
gapi.plusone.go();
But I'm not sure.
Any ideas?
Thanks
You're on the right track. gapi.plusone.go() is one way to explicitly render the +1 button. Here's a code snippet from the official docs that illustrates another method using gapi.plusone.render().
<html>
<head>
<title>+1 Demo: Explicit render</title>
<link rel="canonical" href="http://www.example.com" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{"parsetags": "explicit"}
</script>
<script type="text/javascript">
function renderPlusone() {
gapi.plusone.render("plusone-div");
}
</script>
</head>
<body>
Render the +1 button
<div id="plusone-div"></div>
</body>
</html>
The JavaScript API is further documented elsewhere on the previously linked page.

Is it possible to make a link with 'target' attribute run script on another page?

*Update: Ultimately I've decided that accomplishing exactly what I want here isn't possible due to the issues it poses to security. Kalle's answer below gives a solution that is closest to what I want to accomplish.
In order to solve my problem I've created scripts on both pages and will use a sort of push notification that is routed through the server in order for them to communicate.
Thanks for the help!! *
I have two pages. Both windows already exist independently. Page two has a function declared in JS.
I would like to be able to call the function in window two by clicking a link in window one.
Page 1:
<html>
<head>
<title>This is a title!</title>
</head>
<body style="background: lightblue">
Click Me!
</body>
Page 2:
<html>
<head>
<META HTTP-EQUIV="Window-target" CONTENT="my_target" />
<title>This is a title!</title>
<script type=text/javascript>
function clicked() {
alert('test');
}
</script>
</head>
<body style="background: lightblue">
</body>
Since it is on the same domain you can get this to work but would have to change the way you were doing it a little.
First off you would have to open it in a popup using this syntax rather than a new tab:
newwindow=window.open(url,'name','height=200,width=150');
and then you could simply call newwindow.clicked() after the popup is called.
update
just did a quick test and this will open it in a new tab. (sorry its been a while since I used the open function.
newwindow=window.open(url,'name');
Just noticed also that you should wait for the popup to load. So in my Example it would look a little something like this (with jQuery):
var newwindow = window.open('http://www.tylerbiscoe.com/vb/new.html');
$(newwindow).load(function(){
newwindow.clicked();
});
Ok, brand new answer. I hope this is what you were thinking. This is however, when you open page 2 from page 1.. So basically, page 1 would know who page 2 is..
Online example: http://kopli.pri.ee/stackoverflow/6832271.php
Page 1
<html>
<head>
<title>Page 1</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.ajaxlink {color: blue; cursor: pointer; border-bottom: 1px dotted blue;}
</style>
</head>
<body>
<span id="open_page_2" class="ajaxlink">Open new window</span>
<br>
<br>
Click Me!
<script>
$('#open_page_2').click(function(){
child = window.open('test2.php','page_2','width=600,height=600');
});
$('a[target=my_target]').click(function () {
child.SecondPageFunction();
return false;
});
</script>
</body>
</html>
Page 2
<html>
<head>
<title>Page 2</title>
</head>
<body>
<h1>Your seeing page 2!</h1>
<script>
function SecondPageFunction () {
alert('Second page action got triggered!');
}
</script>
</body>
</html>
The script must be a part of the page you're opening in the new window. You're absolutely correct about it being a security flaw if it was elsewise allowed.
You could add some query string argument that could be picked up onload by javascript in the page you are opening and call your function if the query string arg is present.

Categories