Cross-Document Messaging between two windows or tabs, NOT IFrames - javascript

I have put together a Cross-Document Messaging implementation between a site and an iframe. It woks great. But I desire to communicate between tabs, not iframes.
Here is the code I have, for the iframe communication in 2 parts. The first is the Master page and the other is the remote or slave page.
So, MASTER page here...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Cross-Document Messaging Receiver</title>
<!-- <script type='text/javascript' src='js/xDocMess.js'></script> -->
<link rel="stylesheet" type="text/css" href="css/xDocMess.css">
<script type="text/javascript">
function sendMessage() {
//select the iframe containing the message receiver remote script
var remoteframe = document.getElementById("remotepage");
//Get the users message from the message input box
var message = document.getElementById("message").value;
//Check that the message is not blank
if (message !== "") {
remoteframe.contentWindow.postMessage(message, 'http://localhost:8081');
}
else {
alert("You cannot send a blank message!");
}
}
</script>
</head>
<body>
<h1>Cross-Domain Messaging Example</h1>
<div id="controls">
<label>Enter your message to be sent to the iframe: </label>
<input type="text" id="message" />
<button id="sendmessage" onclick="sendMessage();">Send Message</button>
<p>(Note: Only alphanumeric characters will be printed!)</p>
</div>
<h3>Remote Script iframe</h3>
<iframe id="remotepage" src="http://localhost:8081/remote.html"></iframe>
</body>
And now, the REMOTE site here...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Remote Receiver</title>
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<style type='text/css'>
body {
font-family: sans-serif;
padding: 10px;
}
h3 {
padding-bottom: 5px;
}
#messages {
font-size: small;
border-top: 1px solid #000;
padding-top: 10px;
}
</style>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
function receiver(message) {
//get the message container html element (in this case, the messages div)
var messagecontainer = document.getElementById("messages");
var trusteddomain = "http://localhost:8081";
//Get the time of message receipt
var currenttime = new Date();
//format the time into a user readable format
var formattedtime = currenttime.getHours() + ":" + currenttime.getMinutes() + ":" + currenttime.getSeconds();
var msgcontent = message.data;
//check the content of the message only contains letters and numbers to prevent xss attacks
if (msgcontent.match(/^[A-Za-z0-9]+$/)) {
messagecontainer.innerHTML += "message received # " + formattedtime + ": " + message.data + "<br />";
} else {
messagecontainer.innerHTML += "Illegal characters found in the message received # " + formattedtime + ". Message rejected<br/>";
}
}
}
</script>
</head>
<body>
<h3>Messages Received:</h3>
<div id="messages"></div>
</body>
</html>
The solution lies in how to call a window.open instead of invoking the IFRAME in the MASTER: <iframe id="remotepage" src="http://localhost:8081/remote.html"></iframe> and changing the sendmessage code line:
var remoteframe = document.getElementById("remotepage");
and be able to pass messages to the window. I have a mental block there...
Any help would be appreciated...
TIA
Dennis

If I understand your question, I believe all you need to do is name your window when you call window.open and then use this reference in your code just like you would the contentWindow of an iframe:
var myWindow = window.open('newTab.html');
myWindow.postMessage('You\'re a nice looking window', 'http://yourtargetdomain.com');
You would then put the 'message' handler inside the newTab.html document
window.addEventListener('message', function (event) {
// security check ...
console.log('message: ' + event.data);
});

It can be done only using an iFrame.
Page, loaded in an iFrame, acts as a proxy, translating message events into localStorage events, and vice-versa.
localStorage is separate for each domain, that's why it can't be implemented in two different tabs.

Related

Using Ajax to fetch data from an External API and data from a local excel spreadsheet

Somebody please have a look at my code below, I am trying to Use Ajax to fetch data from an External API. My issue is:
I get an error in the console that says, Uncaught Syntax error: Unexpected Identifier on line 27 document.getElementById('button')addEventListener('click', loadUsers);. If I run this code in browser, I get a blank page.
Can somebody also guide on how I can transform this code using JavaScript (or any of it's libraries) to fetch data from a local excel spread sheet, in such a way that, if my excel sheet has two fields, i.e. Name and ID, the user is required to enter just a matching ID and I thereafter his Name and ID is displayed somewhere on the page. Your efforts will be highly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> Using Ajax 3 to fetch data from an External API</title>
<style>
.user{
display: flex;
background:#f4f4f4;
padding:10px;
margin-bottom:10px;
}
.user ul{
list-style: none;
</style>
</head>
<body>
<button id="button"> Load Github Users</button>
<br /> <br/>
<h1>Github Users</h1>
<div id="users"></div>
<script>
document.getElementById('button')addEventListener('click', loadUsers);
//Load Github users
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/users', true);
xhr.onload = function(){
if(this.status == 200){
var users =JSON.parse(this.responseText);
console.log(users);
var output = ' ';
for(var i in users){
output +=
'<dic class="user">' +
'<img src="'+users[i].avatar_url+'" width="70"
height="70">' +
'<ul>' +
'<li> ID: '+users[i].id+'</li>' +
'<li>Login: '+users[i].login+'<li>' +
'</ul>'
'</div>';
}
[document.getElementById('users').innerHTML = output;
}
}
</script>
</body>
</html>

How to gather the value of a specific <span> from a variable containing the complete web page code

I scraped a web page with the price of bitcoin and have the complete web page code stored in a variable. How do I extract the span:
<span class="text-large2" data-currency-value>8128.61</span>
from the whole code? By the way the number 8128.61 changes every time the page is refreshed as the price is updated
Here is my full code:
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://coinmarketcap.com/currencies/bitcoin/') + '&callback=?', function(data){
console.log(data.contents);
});
body {
background-color: lightblue;
}
<!DOCTYPE html>
<html>
<body>
<html lang="en">
<head>
<title>Web Scraper</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/scripts.js"></script>
</body>
</html>
</body>
you can use something like below to extract the value
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://coinmarketcap.com/currencies/bitcoin/') + '&callback=?', function(data){
console.log($(data.contents).find('span[data-currency-value]').html());
});
you can do this without Jquery also
var htmlData = `your html`;
var divNode = document.createElement("div");
divNode.innerHTML = html;
after this you can access all HTML element which is inside htmlData
like
divNode.getElementsByClassName("test")

images are not rendering on website?

ive looked at other answers and none of them seemed to work which is why i decided to re-ask the question and show you guy my code so you can help me so here it is :
function searchForm() {
var body = document.getElementsByTagName('body')[0]
var search = document.getElementById('GIF-search').value;
var content = document.getElementById('content')
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api");
xhr.done(function(data) {
var image = data;
var GIF = image['data'][0]['embed_url'];
var GIF_image = document.createElement('img');
GIF_image.setAttribute('src', GIF);
GIF_image.setAttribue('id', 'GIF');
content.appendChild(GIF_image)
});
}
var searchGIF = document.getElementById('search_GIF')
searchGIF.addEventListener('click', searchForm, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GIF viewer</title>
<style type="text/css">
#content {
width: 100%
}
img {
width: 250px;
height: 250px
}
</style>
</head>
<body>
<div id="Search">
<input type="text" name="" id="GIF-search">
<button id="search_GIF">Search GIFs</button>
</div>
<div id="content"></div>
<script src="jquery-3.2.1.js"></script>
<script src="GIFsearch.js"></script>
</body>
</html>
my problem here is that im getting a blank image on my site can anyone explain why this is happening and how i can fix it so it will actually show the GIF?
btw i know in the $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api"); the apikey in not valid (this is on purpose);
Couple of things:
There was no jQuery in jsfiddle. Make sure you have it in your code.
Make https:// api call if your page is using https:// protocol.
setAttribute when you are setting id has got a typo. Look carefully.
URL you are getting at image['data'][0]['embed_url'] is not a image url but a webpage url. Try console log it and see. So you cant really set it as a src of some img tag. Find the correct image url and then proceed.

jQuery Ajax Json Parsing in HTML File Not Working with Google Cloud Service

I have been working with jQuery/JavaScript and ajax for the first time and I am trying to work with the weather underground API to display some weather information on a web-page hosted on google cloud.
I have been reading the weather underground code example and I am trying to work with that which is why the code will look so familiar but I am just trying to get it to work so I can move forward. I have also looked at other stack overflow where similar code questions were asked but I am still not getting anywhere. I apologize for the redundancy but I am unsure why it is not working.
Everything seems to be making sense but when the HTML is suppose to "alert" when the page is loaded I am getting nothing. I would really appreciate some input even if I am doing something stupid just want to get this chunk working in order to move forward.
Below is my HTML file that is a mix of JavaScript and HTML.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</html>
My simple CSS file is shown below.
h1 {
color: #000000;
text-align: center;
font-size: 60px;
text-decoration: underline;
}
body {
background-color: LavenderBlush;
font-size: 20px;
}
div {
background-color: lightgrey;
color: #FF0000;
id: "clockbox";
font-size: 20px;
font-family: "Times New Roman", Times, Serif;
width: 420px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
.alert {
padding: 20px;
background-color: #f44336; /* Red */
color: white;
margin-bottom: 15px;
}
I appreciate any feedback!
Thank you
Thanks to some great advice from #GAEfan and yuriy636 I was able to figure out that Google Cloud does not play well with HTTP requests thus it was just a simple change from HTTP to HTTPS in the URL's as you can see in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
Here is a link to more info on Google Cloud and HTTP/HTTPS: https://cloud.google.com/compute/docs/load-balancing/http/
Thank you for everyone's help!
The problem is that you don't have <script> tags inside your <body> tag.
This is what I mean:
<!DOCTYPE html>
<html>
<head>
<title>Hello, The Cloud!</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<body>
<h1>Hello, The Cloud!</h1>
<p> Lets Check the Weather! </p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
</body>
</html>
If you hit an error first, you won't get to the alert. Try adding this logging, to make sure you aren't getting a key error:
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/47acb7d74302f585/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
console.log(parsed_json);
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});

htm file doesn't loaded with query string

I'm trying to get a query string from htm file.
But when I'm writing a "?param=1" in the end of the .htm url - the file not loaded and I don't see anything in this page - The error I get is: "Incorrect document syntax".
When I'm opened this url without the query string in the end, its opened normally.
This is my htm file:
<html>
<head>
<title>Test Url sender</title>
<meta charset="utf-8">
</head>
<body>
<script src="file.js" type="text/javascript"></script>
<style type="text/css">
body {
font-size: 12px;
margin: 0px 10px;
}
</style>
<script type="text/javascript">
window.onload = getQueryString();
function getQueryString() {
var queryString = window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape("param").replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1");
SendUrlsToServer(queryString);
}
</script>
<p>
test paragraph
</p>
</body>
</html>
(The function SendUrlsToServer its from another js file).
I need to get a query string in this url..
This htm file is web resource in crm.
Any help how can I solve this?
Thanks.
In CRM, a webpage (HTML) or Silverlight web resource page can only accept a single custom parameter called data.
anything else will cause problem.
Read More...
You are looking for "urls" in the parameter but sending "param" instead !
Change escape("urls") to escape("param") if you will be sending "param"
Try below code snippet
<html>
<head>
<title>Test Url sender</title>
<meta charset="utf-8">
</head>
<body>
<style type="text/css">
body {
font-size: 12px;
margin: 0px 10px;
}
</style>
<script type="text/javascript">
window.onload = getQueryString();
function getQueryString() {
var queryString = window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape("params").replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1");
SendUrlsToServer(queryString);
}
function SendUrlsToServer(x)
{
if(x.length > 0)
alert(x);
}
</script>
<p>
test paragraph
</p>
</body>
</html>

Categories