smifaye
smifaye

Reputation: 41

How to create a bookmarklet with multiple functions

I'm new to creating JavaScript bookmarklets but have got a certain way in solving my problems but have got stuck on one final bit.

Basically, I want to create a bookmarklet that will replace text in 2 places in the URL - the subdomain and the URI.

I have managed to do this for the first part:

(function() {
  window.location = window.location
  .toString()
  .replace(/^https:\/\/www\./, "https://edit.");
})();

Next, I need to grab some metadata (cab-id) from the page. I've managed to do this an print it to the console:

function getCabID() {
var metas = document.getElementsByTagName("meta");

for (var i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("name") == "cab-id") {
  return metas[i].getAttribute("content");
  }
}

return "";
}

console.log(getCabID());

The next thing I need to do is replace the end of the url (everything from "www.xxxxxx.org.uk/*" with the following:

/EPiServer/CMS/Home#context=epi.cms.contentdata:///

I can't figure out how to do this, I'm really struggling. I've come up with the following but it's not working:

(function() {
  var url=window.location.href;
  stringUrl=String(url);
  stringUrl=stringUrl.replace(/^https:\/\/www.xxxxxx.org.uk\/, "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///");
  document.location=stringUrl;
})();

I'll also need to pop the cab-id at the end of all this directly after ///.

Sorry for the long question but what I need to do is:

  1. Make the 3rd one actually work!
  2. Combine the 3 functions

Any tips would be massively appreciated :D

Upvotes: 1

Views: 1774

Answers (1)

Shugar
Shugar

Reputation: 5299

As I understood your question, the following bookmarklet probably allows to combine the 2nd and 3rd steps:

javascript:(function() {
    window.location.href = "https://edit.xxxxxx.org.uk/EPiServer/CMS/Home#context=epi.cms.contentdata:///" + getCabID();

    function getCabID() {
        var metas = document.getElementsByTagName("meta");

        for (var i = 0; i < metas.length; i++) {
        if (metas[i].getAttribute("name") == "cab-id") {
          return metas[i].getAttribute("content");
          }
        }

        return "";
    }
})();

Upvotes: 1

Related Questions