Search code examples
jquerysafari-extension

How to change one URL to another with JQuery


I have the following script:

<script>  
safari.application.addEventListener("command", performCommand, false);  

function performCommand(event) {    
    if (event.command == "change") {  


    $('a[href="http://example.com"]').attr('href', 'http://sub.example.com');


    }  
}  
</script>

And what I want to happen is that when the menu bar button is pressed, it runs the code in between (in this case, ('a[href="http://example.com"]').attr('href', 'http://sub.example.com');) which finds all links and replaces them with the modified version. How can I accomplish this?


Solution

  • you may want to change your selector so it only finds links that begin with the domain you'd like. This can be accomplished using ^=instead of just=`:

    $('a[href^="http://example.com"]').attr('href',function(i,e){
      // we use a function so we can modify it instead of overwrtie
      return e.replace('example.com','google.com');
    });