3

I'm creating an extension using Crossrider that allows users to bookmark the page they are viewing.

For this purpose, I created a button popup that when clicked opens with the UI for managing the list of bookmarks. When the user clicks on the extension's button I want to pass the URL of the page being viewed to the popup so that I can add it to the list of bookmarks. My problem is that I don't know how to pass the URL to the popup. Can anyone point me in the right direction?

The following snippet is a simplified version of the code to demonstrate what I have:

background.js:

appAPI.ready(function($) {
    appAPI.browserAction.setResourceIcon('images/icon.png');
    appAPI.browserAction.setPopup({
        resourcePath:'html/popup.html',
        height: 300,
        width: 300
    });
});

popup.html:

<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
  function crossriderMain($) {
  }
</script>
</head>
<body>
<h1>Bookmark List</h1>
<ul>
    <li>1: http://example.com/1.html</html>
    <li>2: http://example.com/2.html</html>
</ul>
</body>
</html>
Geekyanton
  • 31
  • 4

1 Answers1

3

The issue here is scope. The scope the popup runs in does not have access to the URL of the page being viewed; hence, to get the URL to the popup scope, the popup code must request the information from another scope via messaging.

The simplest way to do this is for the popup to send a message to the active tab (Extension Page Scope) requesting the URL of the page it's displaying. You can achieve this as follows and I'll leave you to do the code for adding the bookmark to your list.

extension.js:

appAPI.ready(function($) {
  // Listener to receive messages
  appAPI.message.addListener(function(msg) {
    // check if message is requesting page url and respond accordingly
    if (msg.type==='get-url')
      appAPI.message.toPopup({
        url:encodeURIComponent(window.location.href);
      });
  });
  // The rest of your code
  ...
});

popup.html:

...
function crossriderMain($) {
  // Listener to receive messages
  appAPI.message.addListener(function(msg) {
    // check if message contains a url and call function to process the url
    if (msg.url) addBookmark(msg.url);
  });
  // Request url from active tab
  appAPI.message.toActiveTab({
    type: 'get-url';
  });
  function addBookmark(url) {
    // Add your code that handles adding the url to the bookmark list
  }
}
...

[Disclosure: I am a Crossrider employee]

Shlomo
  • 3,763
  • 11
  • 16