I am trying to make a javascript bookmarklet that takes the current page url, modifies the domain to a different one, then opens that in a new tab.
for example, given the url:
https://prod.abc.com/lorum/a-1234/b/c.d/e/1234#fg:hij
I want to run the bookmarklet and have it open
https://dev.abc-1-de.net/lorum/a-1234/b/c.d/e/1234#fg:hij
This is my current code
javascript:(function() {window.open(window.location.toString().replace(/^https://.*?abc.com//, 'https://dev.abc-1-de.net/'), '_blank');})()
When I run
window.location.toString().replace(/^https://.*?abc.com//, 'https://dev.abc-1-de.net/')
I get the url I’m expecting. However, when I run the whole thing together, the new tab that opens is directed to
https://prod.abc.com/lorum/a-1234/b/c.d/e/https://dev.abc-1-de.net/lorum/a-1234/b/c.d/e/1234#fg:hij
.
To me, this seems like the regex is ignoring my ^
anchor for some reason, but I have no idea why that would be happening only when it is passed into window.open
.
3
Answers
Turns out, the issue was a typo in the replacement url I was giving, as well as in the way that window.open works. The replacement url I was giving in my unobfuscated code had the typo
https//:
instead ofhttps:
.This made the window.open function think this was a relative url instead of an absolute, and so it was appending it instead of properly redirecting.
Running this seems to work, as you said:
The console prints out
https://dev.abc-1-de.net/lorum/a-1234/b/c.d/e/1234#fg:hij
as you expect it to.When I run this code:
I am just redirected to a blank window in a new tab. However setting
window.location.href
does redirect, but it does not open in a new windowSo your full code would be
Seems to be working correctly for me.I made a new bookmark with the code
javascript:(function() {window.open(window.location.toString().replace(/^https://.*?.com//, 'https://dev.abc-1-de.net/'), '_blank');})()
I removed the
abc
from the regex and now this bookmark will work for all domains. It essentially replaces the the domain withdev.abc-1-de.net