Javascript | Link/Bookmarklet to replace current w

2019-08-10 09:48发布

问题:

I often work with three variations of a web page, 1) a dev url, 2) a preview/staging url, and 3) and live url.

I would like to create a link (bookmarklet?) that I can then add to my bookmarks bar that will change part of the URL string (basically everything before the page name) and then load the resulting URL in a new tab (or same tab if easier).

Example: working on a page with the Dev URL:

https://dev.mysite.com/cf#/content/www/page1.html

I would like to be able to click the link and have the page reload and return the following staging URL in the same or new window/tab:

https://preview2.mysite.com/page1.html

and then if I click the link again, I would like the page to reload and return the following live url in the same or new window/tab:

http://www2.mysite.com/page1.html

and then if I click the link again, I would like the page to reload and return the following dev url in the same or new window/tab:

https://dev.mysite.com/cf#/content/www/page1.html

So, I would basically like to avoid a lot of cut/copy and paste when I am changing through these variations of the url while developing, testing, and visiting the live versions of the page.

Here is where I am so far.. Stuck on the most basic aspect of it, if on the dev page, reload to preview page:

A variation of the method by joewiz.org "fixing-urls-with-dns-errors" and this one from Stack user63503 "how to replace part of the URL with JavaScript?" and after also trying str.replace from W3Schools.

javascript:(function(){window.location.url.replace("dev.mysite.com/cf#/content/www/","preview2.mysite.com/");})();

or

javascript:(function(){window.location.pathname.replace("dev.mysite.com/cf#/content/www/","preview2.mysite.com/");})()

Thats just one of the steps as you can tell and I'm already stuck. I have tried so many variations but I cannot replace a specific part of the url, let alone add the rules to reload to dev, preview, live depending on where the current browser is.

I realize that very similar questions have already been asked, but I'm afraid that I am unable able to extrapolate actionable information from the ones that I have found. However, please let me know if you feel a previous post is relevent and I'll head over there and study-up.

Thank you all so much!!

回答1:

Your code should work.

But try this

javascript:(function(){var loc=location.href;loc=loc.replace('dev.mysite.com/cf#/content/www/','preview2.mysite.com/'); location.replace(loc)})()

Remember to copy this into the URL of a real bookmark - I normally send people a web page they can drag from so the quotes are indeed important:

<a href="javascript:(function(){var loc=location.href;loc=loc.replace('dev.mysite.com/cf#/content/www/','preview2.mysite.com/'); location.replace(loc)})()">ReplaceUrlBM</a>