I have a file index.html with one iframe set and iframe source points to another domain. I am setting localstorage in index.html and trying to get the value in iframe source.(sample.html)
File 1
index.html
<html>
<head>
//js file
</head>
<body>
setting localstorage
Iframe src="55.10.45.045/sample.html"
</body>
</html>
file 2
sample.html
<html>
<head>
//js file
</head>
<body>
getting localstorage Item //Returns null
</body>
</html
You want to use something like this.
Sending information:
window.onload = function() {
var win = document.getElementById('iFrameId').contentWindow;
win.postMessage(JSON.stringify({
key: 'dataKey',
data: dataPassing
}), "*");
};
Receiving information:
window.onmessage = function(e) {
var payload = JSON.parse(e.data);
localStorage.setItem(payload.key, payload.data);
};
This will pass a JSON object into the iFrame, then the script in the frame will take it and push it into local storage.
Use like this...
index.html
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
click
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("link", "http://www.w3schools.com/");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("link");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
sample.html
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = "<iframe src='"+localStorage.getItem("link")+"' width='100%' height='350px' />";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
Related
I am using W3-Schools "include-html" https://www.w3schools.com/howto/howto_html_include.asp
It states that you can use multiple snippets. My plan was to include a header and a footer for each page by using this method.
On my index.html page I have this:
<!doctype html>
<html lang="en">
<!--Include Content-->
<script src="assets\scripts\include_content.js">
</script>
</head>
<body>
<header>
<div include-html="header.html"></div>
</header>
<footer>
<div include-html="footer.html"></div>
</footer>
<!--Scripts-->
<script>
includeHTML();
</script>
</body>
</html>
The scripts are a direct copy and paste from W3 (with minor changes to attribute names):
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain attribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
};
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
I can get the footer to run if I delete the include-html="header.html" so I know the linking is there. But I can not get both footer and header to run.
Both footer and header pages are currently identical except for the message so I know where the message is coming from.
Can you see if I am missing something or why the second <div include-html="footer.html"></div> is not working?
For all the reasons I mentioned in my comments to your question, you should just abandon the W3 Schools approach.
The simplest solution is to just use HTML <iframe> elements and no JavaScript whatsoever:
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<iframe src="header.html"></iframe>
</header>
<footer>
<iframe src="footer.html"></iframe>
</footer>
</body>
</html>
But, if you do need a JavaScript solution, using AJAX (XMLHttpRequest) is correct, but with the modern syntax, rather than what W3 Schools shows:
function includeHTML(fileName, destination) {
let xhr = new XMLHttpRequest();
// Establish the callback:
xhr.onreadystatechange = function () {
// Is the response ready?
if (this.readyState == 4) {
// Was the response successful?
if (this.status == 200) {
destination.innerHTML = this.responseText;
} else {
console.log("Response was received but not successful.");
}
} else {
console.log("Response is not ready.");
}
}
// Initiate the request:
xhr.open("GET", fileName, true);
xhr.send();
}
// Call the function with the file to include and a reference to the
// element to populate with the contents
includeHTML("header.html", document.querySelector(".header"));
includeHTML("footer.html", document.querySelector(".footer"));
<!doctype html>
<html lang="en">
<head>
<title>Page Title Here</title>
<meta charset="utf-8">
</head>
<body>
<header>
<div class="header"></div>
</header>
<footer>
<div class="footer"></div>
</footer>
<!--Reference and load your scripts just before the closing
body tag so that by the time the HTML parser reaches
this point in the document, all the HTML will have been
parsed into memory. -->
<script src="assets\scripts\include_content.js"></script>
</body>
</html>
I have an endpoint https://api.iextrading.com/1.0/tops?symbols=aapl but when I try to use .getjson with that url I get a 404 error. In the api documentation it mentions that it may be a jsonp request and if so how do I get .getjson to be able to read this call. Thank you in advance.
The code I have tried is...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
$.getJSON('https://api.iextrading.com/1.0/stock/tsla', function(data) {
var obj = JSON.parse(data);
document.getElementById("demo").innerHTML = obj.id;
});
</script>
</body>
</html>
The API or remote resource must set the header. You can try
function(xhr) {
xhr.setRequestHeader('X-Test-Header', 'test-value');
}
The URL you are using doesn't match your description's URL, and the URL actually returns a 404.
Using your description's URL works, however getJSON parses the data so we don't need to do JSON.parse(data);.
Finally, your data doesn't actually have a id attribute so that will return undefined.
I have changed it to symbol which returns AAPL.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
$.getJSON('https://api.iextrading.com/1.0/tops?symbols=aapl', function(data) {
var obj = data[0];
document.getElementById("demo").innerHTML = obj.symbol;
});
</script>
</body>
</html>
i develop on my local desktop machine with brackets. I currently try something with browser notifications. The strange thing is, that this code:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<button id="btn_not">Click me to get notified</button>
<script type="text/javascript">
$(document).ready(function () {
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
$("#btn_not").click(function () {
createNotification();
})
})
function createNotification() {
var notification = new Notification("Hi there!");
}
</script>
</body>
</html>
doesn't work on my local machine but it does work perfectly if I upload it to my webserver, but I don't understand why?
I am trying to use Youtube's api, and run a search query to retrieve the videos found. When I run the js or the html, nothing is printing. The authentication key is correct. When I run the js file all it says is [Finished in 0.4s]. When I run the html file nothing shows up.
js file
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad() {
gapi.client.setApiKey('hidden');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'dog'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response) {
showResponse(response);
}
search html code
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
By default the return value for the video link is the video ID inside the json response format.
"id": {
"kind": "youtube#video",
"videoId": "dgVKzvO5zNc"
}
you can filter the json response and create a work around like a link, here is an example:
request.execute(function(response) {
var items = response.result.items;
for(i in items){
var vidID = items[i].id.videoId;
var link = '' + "link"+[i] + '<br>';
document.getElementById('search-container').innerHTML += link;
}
});
html file
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<div id="buttons"><input id="query" value='cats' type="text"/><button id="search-button" onclick="search()" >Search</button></label>
</div>
<div id="search-container">
</div>
</body>
</html>
In the below code after the download I want to print the downloaded file through jquery/javascript.
But couldn't Identify where I need to put the print command and how need to process. any help would be appreciated - thanks
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("a").click(function(e) {
$('a#test').attr({target: '_blank',
href : 'http://localhost/text.txt'});
});
var downloadURL = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
});
</script>
<body>
<a id="test" href="#">Download now!</a>
</body>
</html>
</head>
To print the content of the iframe just use:
iframe.contentWindow.print();