Adding Additional Attributes in Script Tag for 3rd party JS

I ran into this when attempting to integrate Dropbox’s drop in chooser API to a plugin I’m writing.

The API documentation instructs you to place the following script tag at the top of your file:

<script type="text/javascript" src="https://www.dropbox.com/static/api/1/dropins.js" id="dropboxjs" data-app-key="MY_APP_KEY"></script>

All fine and good, and it actually works when I directly paste it into the page that is called in the admin section. But, I’d like to use some variation of wp_register_script(), wp_enqueue_script() and wp_localize_script() to pass the necessary id and data-app-key.

I’ve tried a couple different variations of this:

add_action('admin_enqueue_scripts', 'add_dropbox_stuff');
function add_dropbox_js() {
    wp_register_script('dropbox.js','https://www.dropbox.com/static/api/1/dropins.js');
    wp_enqueue_script('dropbox.js');
    wp_localize_script('dropbox.js','dropboxdata',array('id'=>"dropboxjs",'data-app-key'=>"MY_APP_KEY"));
}

And:

add_action('admin_enqueue_scripts', 'add_dropbox_stuff');
function add_dropbox_stuff() {
        wp_register_script('dropbox.js','https://www.dropbox.com/static/api/1/dropins.js');
        wp_enqueue_script('dropbox.js');
        wp_localize_script('dropbox.js','dropboxdata',array(array('id'=>"dropboxjs"),array('data-app-key'=>"MY_APP_KEY")));
    }

MY_APP_KEY is replaced with the appropriate application key in my code. Would appreciate any direction. Thanks.

EDIT: Also tried to do it with some jquery, but to no avail. Tried it on document load and on document ready. I get a {“error”: “Invalid app_key”} return.

$('script[src="https://www.dropbox.com/static/api/1/dropins.js?ver=3.6"]').attr('id','dropboxjs').attr('data-multiselect','true').attr('data-app-key','MY_APP_KEY');

9

you can try to use the script_loader_src filter hook e.g:

add_filter('script_loader_src','add_id_to_script',10,2);
function add_id_to_script($src, $handle){
    if ($handle != 'dropbox.js') 
            return $src;
    return $src."' id='dropboxjs' data-app-key='MY_APP_KEY";
}

Update

i just figured it out myself that the src is escaped by esc_url, so looking a bit more i found the clean_url filter which you can use to return the value with your id and app key data :

add_filter('clean_url','unclean_url',10,3);
function unclean_url( $good_protocol_url, $original_url, $_context){
    if (false !== strpos($original_url, 'data-app-key')){
      remove_filter('clean_url','unclean_url',10,3);
      $url_parts = parse_url($good_protocol_url);
      return $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . "' id='dropboxjs' data-app-key='MY_APP_KEY";
    }
    return $good_protocol_url;
}

Leave a Comment