Change the whole url in the address bar (Javascript) - javascript

I need a code that changes the whole url in the address bar, (in javascript).
I have already searched upon this question all over the internet and found this code
<script type="text/javascript">
function ChangeUrl(title, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
</script>
<input type="button" value="Page1" onclick="ChangeUrl('Page1', 'Page1.htm');" />
<input type="button" value="Page2" onclick="ChangeUrl('Page2', 'Page2.htm');" />
<input type="button" value="Page3" onclick="ChangeUrl('Page3', 'Page3.htm');" />
But this doesn't changes the whole URL, it just changes
localhost/index.php
to
localhost/Page1.htm
Is there a way possible to change the whole URL? like from
localhost.index.php
to
Page1.htm

No.
The History API does not let you change the apparent Origin of the page. That would be too useful for people making Phishing attacks.
You can only change the path and what follows it.

Use History.replaceState for your problem
https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'get') at HTMLInputElement.geocodio

I am having issues trying to run an API using Geocodio. This is set up through WordPress and I would really appreciate any help I can get!
Everything works up until the actual API itself has to run. The Geocodio documentation states that it runs "using a jQuery AJAX call". I have tried multiple script sources that claim to fix the problem, but I get the error that "superfish() is not a function" or that "Cannot read properties of undefined (reading 'get')".
<head>
<script src="jQuery.js"></script>
<script src="superfish.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('ul.sf-menu').superfish();
});
</script>
</head>
<body>
<input type="text" id="myTxt" style="width: 400px;" placeholder="Type Your Address Here!"></input>
<input type="submit" id="myBtn" value="Search Now!"></input>
<script>
var submit = document.getElementById("myBtn")
var myInput = document.getElementById("myTxt")
submit.addEventListener("click", geocodio)
function geocodio() {
if(myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
$.get('https://api.geocod.io/v1.7/geocode?q='+ encodeURIComponent(myInput)
+'&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results)});
}
};
</script>
</body>
You must be using some strange version of jQuery that forces you to refer to it as jQuery and not $. Odd, I thought all versions of jQuery also set up the $ global.
Try replacing $ with jQuery inside geocodio():
function geocodio() {
if (myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
jQuery.get('https://api.geocod.io/v1.7/geocode?q=' + encodeURIComponent(myInput.value)
+ '&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results);
});
}
}
(also fixed: encode myInput.value instead of encoding whole input)
If that doesn't work, perhaps jQuery.js failed to load. Check the console messages and/or network trace tab in the developer tools.
If that doesn't work, try stepping thru the code using the JavaScript debugger built in to your browser (short tutorial video).

Silence net::ERR_CONNECTION_REFUSED

Connecting to a non-existent web socket server results in loud errors being logged to the console, usually to the tune of ... net::ERR_CONNECTION_REFUSED.
Anyone have an idea for a hackaround to silence this output? XMLHttpRequest won't work since it yields the same verbose error output if the server is not reachable.
The goal here is to test if the server is available, if it is then connect to it, otherwise use a fallback, and to do this without spamming the console with error output.
Chrome itself is emitting these messages, and there is no way to block them. This is a function of how chrome was built; whenever a ResourceFetcher object attempts to fetch a resource, its response is passed back to its context, and if there's an error, the browser prints it to the console - see here.
Similar question can be found here.
If you'd like, you can use a chrome console filter as this question discusses to block these errors in your console, but there is no way to programmatically block the messages.
I don't know why do you want to prevent this error output. I guess you just want to get rid of them when debugging. So I provide a work around here may be just useful for debugging.
Live demo: http://blackmiaool.com/soa/43012334/boot.html
How to use it?
Open the demo page, click the "boot" button, it will open a new tab. Click the "test" button in the new tab and check the result below. If you want to get a positive result, change the url to wss://echo.websocket.org.
Why?
By using post message, we can make browser tabs communicate with each other. So we can move those error output to a tab that we don't concern.
P.S. You can refresh the target page freely without loosing the connection between it and boot page.
P.P.S You can also use storage event to achieve this.
boot.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>boot page</title>
</head>
<body>
<button onclick="boot()">boot</button>
<p>BTW, you can boot the page without the button if you are willing to allow the "pop-up"</p>
<script>
var targetWindow;
function init() {
targetWindow
}
function boot() {
targetWindow = window.open("target.html");
}
boot();
window.addEventListener('message', function(e) {
var msg = e.data;
var {
action,
url,
origin,
} = msg;
if (action === "testUrl") {
let ws = new WebSocket(url);
ws.addEventListener("error", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: false,
}, origin);
ws.close();
});
ws.addEventListener("open", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: true,
}, origin);
ws.close();
});
}
});
</script>
</body>
</html>
target.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>target page</title>
</head>
<body>
<h4>input the url you want to test:</h4>
<textarea type="text" id="input" style="width:300px;height:100px;">
</textarea>
<br>
<div>try <span style="color:red">wss://echo.websocket.org</span> for success result(may be slow)</div>
<button onclick="test()">test</button>
<div id="output"></div>
<script>
var origin = location.origin;
var testUrl = origin.replace(/^https?/, "ws") + "/abcdef"; //not available of course
document.querySelector("#input").value = testUrl;
function output(val) {
document.querySelector("#output").textContent = val;
}
function test() {
if (window.opener) {
window.opener.postMessage({
action: "testUrl",
url: document.querySelector("#input").value,
origin,
}, origin);
} else {
alert("opener is not available");
}
}
window.addEventListener('message', function(e) {
var msg = e.data;
if (msg.action === "urlResult") {
output(`test ${msg.url} result: ${msg.data}`);
}
});
</script>
</body>
</html>

Not able to fetch the URL / location of the pop-up window

Is there a way to fetch the URL / Location of the pop-up window?
CODE:
<html>
<head>
<script>
function openWin()
{
myWindow=window.open('http://www.google.com','','width=200,height=100');
console.debug(myWindow.location.href);
console.debug(window.location.href);
}
</script>
</head>
<body>
<input type="button" value="Open window" onclick="openWin()" />
</body>
</html>
The first console prints about:blank
While the second console prints the URL of the current page(i.e URL of the above code, it does not print the URL of the pop-up window)
Why isn't the first console printing the location (i.e http://www.google.com) ?
Can anyone help me out with this?
Thanks in advance.
Because browser security prevents you from getting the URL from any window that's not on the same domain as your script. So, if your code was running on example.com, you'd only be able to get the URL of any window that was also on example.com.
As #Hg3 says, you cannot access location.href for myWindow. window.open returns an empty DOMWindow.
However, you can overwrite window.open and maintain a simple array of all the windows you have opened.
//override window.open
var windows = [];
window._open = window.open;
window.open = function(url, name, params){
windows.push(name, url);
return window._open(url, name, params)
}
//function return href by name
function hrefByName(name) {
var index=(windows.indexOf(name));
return (index>-1) ? windows[index+1] : 'undefined';
}
//modified openWin function
function openWin(url, name) {
var params='width=200,height=100';
window.open(url, name, params);
//test, ouput current url and the windows array
console.log(hrefByName(name));
console.log(windows);
}
test markup :
<input type="button" value="google" onclick="openWin('http://google.com', 'google')" />
<input type="button" value="bing" onclick="openWin('http://bing.com', 'bing')" />
<input type="button" value="stackoverflow" onclick="openWin('http://stackoverflow.com', 'stackoverflow')" />
Of course, I guess you have a setup with dynamically generated URL's - just build random names or pass an unique number as name.

Javascript changing values inside a iframe

I have my website
www.aplicatii-iphone.ro
and another
page.html on localhost
<html>
<head>
<title>Object References across Iframes</title>
<script type="text/javascript">
window.onload = function(){
var form = document.getElementById('testForm');
form.testBtn.onclick = sendData;
}
function notify() {
//alert('iframe loaded');
var iframeEl = document.getElementById('ifrm');
if ( iframeEl && iframeEl.parentNode && document.createElement ) {
var newTxt = document.createTextNode('The iframe has loaded and your browser supports it\'s onload attribute.');
var newPara = document.createElement("p");
newPara.className = 'demo';
newPara.appendChild(newTxt);
iframeEl.parentNode.insertBefore(newPara, iframeEl);
}
}
function sendData() { // to form inside iframed document
// frames array method:
// window.frames['ifrm'].document.forms['ifrmTest'].elements['display'].value = this.form.testEntry.value;
var ifrm = document.getElementById('ifrm');
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('search-input'); // <------<< search input
form.display.value = this.form.testEntry.value;
form.submit();
}
// test in iframed doc
var counter = 0;
</script>
</head>
<body>
<form id="testForm" action="#">
<p><input type="text" name="testEntry" size="30" value="[enter something]" /> <input name="testBtn" type="button" value="Click Me" /></p>
</form>
<iframe name="ifrm" id="ifrm" src="http://www.aplicatii-iphone.ro" onload="notify()" width="900">Sorry, your browser doesn't support iframes.</iframe>
</body>
</html>
And every time I press the button Click Me, I want that the state of www.aplicatii-iphone.ro to be like a user searched for that value written in "testEntry" from outside of the iframe.
I tried something there ... but I can't figure it out ... any help please?
I took the example from here http://www.dyn-web.com/tutorials/iframes/refs.php
If you know you're using a modern browser, you could use postMessage to communicate between the frames. Here's a good write-up: http://ajaxian.com/archives/cross-window-messaging-with-html-5-postmessage
If you need to support legacy browsers, you could use Google Closure's CrossPageChannel object to communicate between frames.
Unfortunatly, this is not possible due to the Same orgin policy.
And changing the document.domain-value only helps if you try to connect a subdomain with the main-domain.
Edit
If you avoid the same-orgin-problem by using a page on the same website, this should work for you:
window.frames['ifrm'].document.getElementById("search-input").value = document.getElementsByName("testEntry")[0].value;
window.frames['ifrm'].document.getElementById("cse-search-box").submit();

Showing Contacts on iOS with Cordova (PhoneGap)

I am working on a JQuery Mobile app. I want to distribute this app via the AppStore with the help of Cordova (PhoneGap). I want to have a button such that when a user clicks it, their contacts appear. When they choose one, I want to get the email address associated with it if possible. Currently, I have the following:
<input id="viewButton" type="button" value="+" onclick="getContact();" />
<script type="text/javascript">
function getContact() {
var options = new ContactFindOptions();
var fields = ["name", "emails"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
function onContactSuccess() {
alert("Great");
}
function onContactError() {
alert("oops");
}
</script>
Much to my surprise, I do not see a contact popup. What am I doing wrong?
You forgot to change the onSuccess and onError method names. The instance constructor of contacts.find should read:
navigator.contacts.find(fields, onContactSuccess, onContactError, options);

Categories