Search code examples
crossrider

Getting current page url from an extension using crossrider


I am trying to set up an extension for firefox, chrome, safari and internet explorer, I am using crossrider.

Basically I want to display a browser action when clicked displays a popup containing an input text with the current page url and a button that will open a new tab to another url passing the url as a parameter.

Here is what I did based on what I found in the documentation ;

extension.js :

appAPI.ready(function($) {
    appAPI.message.addListener(function(msg) {
        if (msg.request === 'getUrl'){
            appAPI.message.toPopup({url:location.href});
        }
    });
});

background.js :

var activeTabUrl;

appAPI.ready(function($) {
    appAPI.browserAction.setResourceIcon('logo-19.jpg');
    appAPI.browserAction.setBadgeText('extn', [255,0,0,125]);
    appAPI.browserAction.setTitle('Add Url to Site');

    appAPI.browserAction.setPopup({resourcePath:'pin.html', height: 300, width: 300});

});

pin.html :

<!DOCTYPE html>
<html>
    <head>
        <title>
        </title>

        <script type="text/javascript">
        function crossriderMain($) {
            activeTabUrl = null;

            appAPI.message.addListener(function(msg) {
                if (msg.url) {
                    activeTabUrl = msg.url;

                    $('#url').val(activeTabUrl);

                    if(activeTabUrl){
                        $('#addurl').prop('disabled', false);
                    }
                }
            });

            appAPI.message.toActiveTab({request:'getUrl'});


            $('#addurl').click(function(){
                var fullUrl = 'http://my.site.com/addurl?url=' + activeTabUrl;
                appAPI.openURL(fullUrl, "tab"); 
            });

        }
        </script>
    </head>
    <body>
        <input id="url" name="url" readonly="true" type="text"/>
        <input id="addurl" type="submit" value="Add Url" disabled/ >

    </body>
</html>

Sometimes the field containing the url is not filled, it does not happen on a specific page, for the same page, sometimes it will be displayed, sometimes not. I can't pinpoint a specific cause.

Am I doing something wrong ?


Solution

  • The code looks fine, other than a minor point of declaring activeTabUrl in the pin.html code and not the background.js code as they are different scopes.

    From experience, the only thing I can think of that may be causing the issue is that sometimes browsers return the message response before the message listener has initialized. To mitigate this, in the pin.html code, add a delay to sending the message requesting the URL, as follows:

    setTimeout(funtion() {
      appAPI.message.toActiveTab({request:'getUrl'});
    }, 0);
    

    [Disclosure] I am a Crossrider employee