Javascript: Rewrite anchor or hash to ampersand - javascript

How can i rewrite part of an URL to alter the anchor or has tag to an ampersand? Example:
http://www.test.com/?database=demo#option=set
changed to:
..website../?database=demo&option=set
Notice the change from #option to &option.
I know the # is only processed client side (it never reaches server), so Javascript seemed like the only way to go.
Can Javascript change this on the fly, even without reloading the page? That would eliminate an IF check to find if an instance exists. A reload if the page would work to1...
Thanks for your time and expertise.

"Can Javascript change this on the fly, even without reloading the page?"
No. What you think is a cosmetic change, in reality means totally different resource as represented by URL, because &option would mean new GET parameter.
So page redirect would be needed in order to change this part of URL.

Related

Hash refresh in Javascript

I'm almost done with my previous issue, but now I'm dealing with something more subtle and annoying.
I've got a page with some links like these ones:
First content
Second content
In the page page.html there is some javascript, something like this:
document.write (window.location.href);
So, I click on the first link, and I see (in a different frame) the page "page.html", correctly starting at anchor #1. At the end the javascript writes "page.html#1", and this is correct.
Then I click on the second link, and I see the page "page.html" changing its starting point, now correctly set at anchor #2. But at the end of the page I still see "page.html#1", not "page.html#2" as I expected. I think this happens because the page is exactly the same as before, only the starting point changed, so the "location.href" was not changed, despite a difference in the hash.
Is there a way to solve the problem, and get the original location.href, the one with the correct hash?
use onclick event attribute:
First content
Second content

window.history.pushState refreshing the browser

I am working on some javascript code, and using window.History.pushState to load new HTML pages, instead of using href tags. My code (which is working fine) looks like this.
window.History.pushState({urlPath:'/page1'},"",'/page1')
strangely, this fails, ie reloads the browser
window.History.pushState({urlPath:'/page2.php'},"",'/page2.php')
But this works, content is updated, browser not refreshed ! (notice the URL is absolute and not relative)
window.History.pushState({urlPath:'www.domain.com/page2.php'},"",'www.domain.com/page2.php')
The documentation for window.History.pushState says that the third parameter URL can be either absolute or relative -
URL — The new history entry's URL is given by this parameter. Note
that the browser won't attempt to load this URL after a call to
pushState(), but it might attempt to load the URL later, for instance
after the user restarts the browser. The new URL does not need to be
absolute; if it's relative, it's resolved relative to the current URL.
The new URL must be of the same origin as the current URL; otherwise,
pushState() will throw an exception. This parameter is optional; if
it isn't specified, it's set to the document's current URL.
Absolute URLs seem to be working but relative seem to be not. Why is this happening?
The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.
If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).
history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.
In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').
If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.
If you post more code, I'll update this answer (I have your question favourited) :).
As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.
If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").
But this function is not intended to reload the browser.
All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).
For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.
Hence the need for the function
history.pushState({},"Results for `Cats`",'url.html?s=cats');
It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.
When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.
If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.
As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.
See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page.
And on that page you can get the conditions by getting the current URL and making all of your conditions.

What can cause a URL hash to change?

I'm trying to monitor my URL hash (a.k.a. fragment) using the onhashchange event so that I can make appropriate ajax calls based upon the parameters I'm storing in the hash. Unfortunately, there is something unexpected changing my hash. In all of my code, there is only one place that where I use window.location.hash and it is simply checking the value of the hash, not changing it. I know that the back and forward buttons can change the hash, but I'm not touching them. How do I find where the hash change is coming from?
Update
Ok... figured it out. And yes, I'm a dummy, but I leave my findings here for those as dumb as I. I was looking for something programmatic changing my hash, but what was really happening was that I was clicking on an anchor with href="#". There is an event handler hooked to these, and I set the return value to false and that prevented it from changing the URL.
Links that target internal anchors change the hash. For example:
Contact Us
Clicking that would change the hash to #contact.
Also, if you're using any third-party javascript libraries, it's possible that some code in there might be changing it.
What does the hash change to? From what? And When? If you can identify the exact circumstances that trigger the change, that should give you some idea what might be changing it.

JavaScript Close/Redirect Page Upon URL Change

I have a frame with a page from a different domain. Sometimes, that page likes to use a frame-buster to break out of its frame and hijack my entire page.
I have been experimenting with different ways to handle what happens when this frame wants to break out. What I have determined would be the best way to handle this is to use JavaScript to determine when the parent page url changes (via onunload) I want to direct the user back to my homepage or close the page altogether. I am a php dev and don't really ever use JavaScript.
I have tried using but that doesn't seem to work. Any ideas?
you can use something like this:
<script>
window.onunload=function() {
return confirm('Are you sure you want to leave the current page?');
}
</script>

Using jQuery to disable everything on a page. Break my code

For my current project, I require the facility to be able to remove all functionality from a page, so that it is complete and literal static page. Removing the ability to follow any links, and disabling and javascript listeners allowing content to be changed on the page. Here is my attempt so far:
$("*").unbind().attr("href", "#");
But in the pursuit of a perfect script, and to allow it to work in every eventuality for any possible page (and with the uncertainty of a on liner being effective enough), I thought i'd consult the experts here at stackOverflow.
In summary, my question is, 'Can this be (and has it been) done in a one liner, is there anything this could miss?'. Please break this as best you can.
No. Nothing in this stops meta redirects, or timeouts or intervals already in flight, and it does nothing about same origin iframes (or ones that can become same origin via document.domain) that can reach back into the parent page to redynamize content.
EDIT:
The sheer number of ways scripts can stay submerged to pop up later is large, so unless you control all the code that can run before you want to do this, I would be inclined to say that it's impossible in practice to lock this down unless you have a team including some browser implementors working on this for some time.
Other possible sources of submarine scripts : XMLHttpRequests (and their onreadystatechange handlers), flash objects that canscript, web workers, and embedding code to run in things like Object.prototype.toString.
I did not want to write a lengthy comment so I'm posting this instead.
As #Felix Kling said, I don't think your code will remove the href attributes on every element but rather remove every element and then select their href attributes.
You probably need to write:
$("*").attr("href", "#").detach() ;
to remove the attributes instead of the elements.
Other than that, I doubt that you could remove the event handlers in one line. For one thing you would need to account for DOM level 2 Event registration (only settable with scripting) and DOM level 1 Event registration (via attributes or scripting).
As far as I'm concerned, your best bet is to make a shallow document copy using an XML parser and replace the old document (which you could backup-save to the window).
First: Your code will remove everything from the page, leaving a blank page. I cannot see how it would make the page "static".
$('*').detach();
will remove every element form the DOM. Nothing left. So yes, you remove every functionality in a way, but you also remove all the content.
Update: Even with the change from detach to unbind, the below points are still valid.
Event listeners added in the markup via oneventname="foo()" won't be affected.
javascript: URLs e.g. in images might still be triggered.
Event listeners added to window and document will persist.
See a DEMO.

Categories

Resources