new location hash doesn't output when clicking on link.
I am at a loss understanding why the browser doesn't output the updated variable.
<html>
<body>
<p></p>
1
2
</body>
<script>
var p = document.querySelector('p');
p.innerHTML = location.hash;
</script>
</html>
When I click on the first link, the address in the browser changes to #2019-01, but p.innerHTML displays nothing.
I expected it to display #2019-01.
If I hit crtl r, to reload the page, then p.innerHTML displays #2019-01.
Why do I have to force a reload to get the output?
Is there a way to get the updated location.hash value without reloading the page?
I would recommend you create a showHash function and then call it immediate when the page loads. Additionally, you can add an event listener to window.onhashchange to call the showHash function any time the hash changes.
showHash();
function showHash() {
var p = document.querySelector('p');
p.innerHTML = location.hash;
}
window.onhashchange = showHash;
<html>
<body>
<p></p>
1
2
</body>
</html>
Related
I have a link that generates new images if you change the number at the end of the URL. I want that each time I refresh the page from the browser, it should generate a different image. I don't want to use any button to click on but to use the refresh button in the browser. I tried using the window.onload property but am facing some issue.
I have the code almost working and I am able to generate a new url with the random number in the end every time I refresh the page but when I try to load it's page it doesn't work. It gets stuck to the first random url. I know that the url is being changed randomly because from the alert message I can verify that. kindly help!
<script>
var url = "https://memegenerator.net/img/images/501.jpg";
function load()
{
var num=url.match(/\d/g).join("");
var numreplace=Math.floor(Math.random()*1000);
url=url.replace(num,numreplace);
openpage(url);
}
function openpage(url) {
alert(url);
//window.location.href=url;
//or window.location.replace(url);
}
window.onload=load();
</script>
I expect a new image to be loaded every time I reload the page.
The problem is that you redirect the page to an image at another URL, for example https://memegenerator.net/img/images/377.jpg, so when you then refresh the page it will just refresh that URL and stay on that image. I've changed your code so that it will insert the image into the body of your page so that it will stay on your URL and do a different image every time. You can test it by pressing Run a few times.
<body>
</body>
<head>
<script>
var url = "https://memegenerator.net/img/images/501.jpg"
function load() {
var num = url.match(/\d/g).join("")
var numreplace = Math.floor(Math.random() * 1000)
url = url.replace(num, numreplace)
openpage(url)
}
function openpage(url) {
console.log(url)
document.body.innerHTML = '<img src="'+url+'">'
}
window.onload = load()
</script>
</head>
Alert messages can prevent document to load new urls like window.location.href
Alert messages also prevent form action
So just remove alert(url)
Your code is working fine:
<script>
var url = "https://memegenerator.net/img/images/501.jpg";
function load()
{
var num=url.match(/\d/g).join("");
var numreplace=Math.floor(Math.random()*1000);
url=url.replace(num,numreplace);
openpage(url);
}
function openpage(url) {
window.location.href=url;
}
window.onload=load();
</script>
Try to short your code like this:
function load() {
var num=Math.floor(Math.random()*1000);
var url="https://memegenerator.net/img/images/"+num+".jpg";
openpage(url);
}
I the below script, once the button is pressed, a new browser tab with Google is opened. I then want to fill the search box on this newly opened tab.
How do I switch focus to this new tab, so that I can wait for it to load completely and then fill the search box?
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var url = "https://www.google.com";
window.open(url);
window.onload(fill_search_box()); // here it will try to operate on the old tab
};
function fill_search_box() {
var search_box = document.getElementsByName("q")[0];
search_box.value = "Some text";
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
You can't exactly target another element in another document from your script, however, you can set the textbox value of the Google textbox using a query string:
www.google.com?q=SearchTerm
When creating the SearchTerm you should also use encodeURI to ensure that your attached search query meets URL standards
Also, if you wish to open the window in another tag you can use window.open(url, "_blank") to open.
See example below:
Note:- The page will not open due to snippet restrictions - so run in your own browser.
<button id="start">Google</button>
<script>
function open_google_in_new_tab() {
var text = "Some text";
var url = "https://www.google.com?q=" + encodeURI(text);
console.log(url)
window.open(url, '_blank');
};
var start_button = document.getElementById("start");
start_button.addEventListener("click", open_google_in_new_tab);
</script>
You cannot do that with Javascript unfortunately.
However, this might make you achieve something similar if you are willing to try.
You can manipulate the search string via parameter named "q" in the query string of the Google website. So, in order to make the user to go the Google and search this particular word, you attach the keyword to it. Something like this:
var url = "https://www.google.com?q=searchKeyword";
Following is the code I have got for location redirect to SMS app when the user is on a mobile browser-
window.onload = function() {
window.location ="sms:12345?body=" + encodeURIComponent("TEST");
}
This code works perfectly on JS fiddle when running on a mobile
JS Fiddle link -https://jsfiddle.net/netstarter/rwqyp2tn/1/
Easiest and appropriate way of doing this would be creating an hidden link and triggering it directly.
window.onload = () => {
let element = document.getElementById("hiddenAppLink");
element && element.click();
};
<!DOCTYPE html>
<html>
<body>
</body>
</html>
You can also trigger it based on a condition by tracking the state if its closed or not in a variable instead bugging the user on every load (You can also use localStorage can't do it in fiddle => security violation). something like this.
window.onload = () => {
if(window.hideDialouge != true){
let element = document.getElementById("hiddenAppLink");
element && element.click();
//Track if its alredy shown
window.hideDialouge = true;
}
};
<html>
<body>
</body>
</html>
SMS URL seems to be only working when you are about to open new SMS URL. It fails to work when you manually enter the URL or use window.location redirect.
You can use two methods to achieve this:
Open hidden link.
Use window.open (This might ask user to allow popups on your page)
1. Open hidden link.
Create a hidden link and open it.
window.onload = function() {
let elem = document.getElementById("loadSMS");
elem && elem.click();
}
<a href="sms:1-111-1111?body=Blah" style="display:none" id="loadSMS">
</a>
2. Use window.open instead of changing window.location
window.onload = function() {
window.open("sms:1-111-1111?body=Blah");
}
I'm using document.open() + write() + close() to create a new page from the client. This works, but it will replace the current history element with the new page, so when the user clicks back they don't see the page they were just on. Example:
At Home Page
Click button to navigate to page shown below.
Click on the click me button on that page.
Click back - this returns user to home page which I don't want.
I've tried inserting a history element with history.pushState() but that doesn't work either. It allows the document.open page to have a new url. Clicking back returns the user to the URL of the page I want displayed, but it is still the "New Page".
Full HTML page code below. This type of example doesn't work in fiddles but can be tested locally.
<html>
<body>
<button onclick="clickme()">Click me</button>
<script>
function clickme() {
history.pushState(null, null, "Results/");
document.open("text/html");
document.writeln("New Page");
document.close();
}
</script>
</body>
</html>
Note: Looking for a solution with cross browser support, including the latest Chrome 45 which may has tightened security a bit.
I did find a workaround but still not exactly what I want.
function clickme() {
results = window.open();
results.document.writeln("New Page");
results.document.close();
}
This obviously makes an entire new tab/window to display the results instead of a new page in the history of the current tab. It is pretty much the same thing in a cell phone since back takes you to the original page, but not on a desktop browser.
I would create an actual web page for page 3 instead of pushing fake history events.
history.pushState isn't supported in older IE's (9 and below) and is buggy on some Androids, this may not be an issue for your project. http://caniuse.com/#search=history.pushState
If you can't change the back end to redirect to page 3, you could do this in javascript:
save your html in localStorage
redirect to page 3
insert your html when page 3 loads.
page 2:
function clickme() {
var html = 'my generated html';
localStorage.savedHtml = html;
window.location = 'page3.htm';
}
page 3:
<html>
<head>
<!-- I'm assuming you're using jquery -->
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="restoredHtml"></div>
<script>
$(function(){
var savedHtml = localStorage.savedHtml || 'No html to restore';
$('#restoredHtml').html(savedHtml);
localStorage.removeItem('savedHtml');
});
</script>
</body>
</html>
You can store a string object on pushState and than read back the object value so you can construct a page from that value instead of the browser stream.
So first we add a new element with pushState()
var markup = "New page content";
history.pushState( { pageContent : markup } , null, "Results/");
document.open("text/html");
//Write the markup using document object
document.writeln(markup);
document.close();
Than you can attach a listener on onpopstate event and check if state has pageContent, and if it has than construct the document from that :
window.onpopstate = function(event) {
if(event.state.hasOwnProperty("pageContent")){
document.open("text/html");
//Write the markup using document object
document.writeln(event.state.pageContent);
document.close();
}
};
Is there a specific reason that you need to use document.open, document.write and document.close? Wouldn't it be easier to keep a single page that can maintain the state, and swap the markup in and out?
The following code will let you use the forward and back buttons in Chrome:
<body>
<div id="content-area">
</div>
<button onclick="clickme()">Change Page</button>
<script>
var state = 1;
function changeContent(state) {
var contentArea = document.getElementById("content-area");
contentArea.innerHTML = "Page " + state;
}
function clickme() {
state = state+1;
history.pushState(state, null, "/Page" + state + "/");
changeContent(state);
}
window.onpopstate = function(event) {
if (event.state != null) {
state = event.state;
} else {
state = 1;
}
changeContent(state);
};
changeContent(state);
</script>
</body>
I want to know if the user has focus on the http or https.
So everytime the user clicks on one of the childwindows - i want to know which one is "active".
I checked the W3C. The Page Visibility API
Is there a way to detect if a browser window is not currently active?
But for me it only was working with tabs but not windows.
EDIT: And only tested on the Parentwindow.
Any Help?
Thanks in advance.
Here is what i got.
<html>
<head>
<title>checkfocus</title>
</head>
<body>
Click me.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
var w;
var w2;
function loadChild() {
w = window.open("","",'width=400,height=200');
w.location.href="https://www.facebook.com";
w.moveTo(0,0)
w.addEventListener('focus',function(){
console.log("w")
})
w2 = window.open("","",'width=400,height=200');
w2.moveTo(400,0)
w2.location.href="http://www.facebook.com";
w2.addEventListener('focus',function(){
console.log("w2")
})
}
</script>
</body>
</html>
the Events is fired 2 times in chrome one time when the window is opened and one time location.href is set... but nothing afterwards
try to put the code in a div, put the div in a table and put the table in a top-frame...!