track all external links on blog via username

I do not know of an existing plugin that does what you want.

Using a custom script is quite difficult, I would not try this. Mainly because you do not know which WP functions you can use/which functions need others to work, …

If you want to track links then I would use an ajax event send a “click” event to WordPress when someone clicks on a link. Also you do not need to include the username in the URL, since you can always use get_current_user_id() to determine the logged in users ID.

The solution could be a simple script, with this structure:

// 1. Add a javascript for click-tracking on every WordPress page.
add_action( 'wp_footer', 'add_tracking_script' );
function add_tracking_script() {
    ?><script>jQuery(function(){
      function domain(url) {
        return url.replace('http://','').replace('https://','').split("https://wordpress.stackexchange.com/")[0];
      }

      var local_domain = domain('<?php echo site_url() ?>');

      jQuery('a').on('click', function(){
        var link_url = jQuery(this).attr('href');

        if (domain(link_url) === local_domain) {return true;}
        window.wp.ajax.send('tracking-click', {url: link_url})
        return true;
      })
    })</script><?php
}

// 2. Add the ajax handler for the tracking.
add_action( 'wp_ajax_tracking-click', 'ajax_handler_tracking' );
function ajax_handler_tracking() {
  $user_id = get_current_user_id();
  $url = $_REQUEST['url'];

  // Save the user_id + $url to your DB table...

  exit;
}

Update

If you get an JS error window.wp.ajax.send is undefined then you also need to add this php code to tell WordPress that you want to use window.wp

// 3. Make sure WordPress loads the window.wp object:
add_action( 'wp_enqueue_scripts', 'add_wp_utils' );
function add_wp_utils() {
    wp_enqueue_script( 'wp-utils' );
}

FYI: You can find a bit more information on window.wp.ajax in this post https://wordpress.stackexchange.com/a/245275/31140