skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 of https:.

    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.


  2. Running this seems to work, as you said:

    var oldUrl = "https://prod.abc.com/lorum/a-1234/b/c.d/e/1234#fg:hij";
    var newUrl = oldUrl.replace(/^https://.*?abc.com//, 'https://dev.abc-1-de.net/');
    
    console.log(newUrl)
    

    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:

    window.open("https://dev.abc-1-de.net/lorum/a-1234/b/c.d/e/1234#fg:hij", "_blank")
    

    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 window

    window.location.href = "https://dev.abc-1-de.net/lorum/a-1234/b/c.d/e/1234#fg:hij";
    

    So your full code would be

    javascript:(function() {
      window.location.href = window.location.toString().replace(/^https://.*?abc.com//, 'https://dev.abc-1-de.net/');
    }() 
    
    Login or Signup to reply.
  3. 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 with dev.abc-1-de.net

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search