Search code examples
javascriptgoogle-chromebookmarkletbookmarks

Using javascript to make custom bookmark links in Chrome


Before diving into building Chrome browser extensions, I'd like to make a list of bookmarks that, when clicked, use javascript to perform particular actions. I am not 100% sure, but I think these may be referring to as bookmarklets?

To start off simple, an example of something I need to do is:

  • I'm currently viewing www.somedomain.com
  • I'd like to click a bookmark and be taken to www.somedomain.com/?testinfo=visible

Meaning, whatever site I am at, it adds /?testinfo=visible to the url and loads that. It'll need to check if it ends in / already, so it doesn't end up with //, at least.

Much thanks.


Solution

  • Not sure I understand what you are asking for, but if you are looking for a way to check what a string ends with in JavaScript, you could create a string-prototype, as suggested in this SO answer:

    if (typeof String.prototype.endsWith !== 'function') {
        String.prototype.endsWith = function(suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }
    

    On the variable holding your URL, you could then do this to see if it already has a trailing slash:

    if (myUrlVariable.endsWith('/')) {
       // Already ends with a slash, act accordingly
    } else {
       // Does NOT end with a slash, act accordingly
    }