Crossrider扩展平台

时间:2014-08-03 07:33:24

标签: javascript api cross-browser browser-extension crossrider

我正在使用Crossrider创建一个扩展程序,允许用户为他们正在查看的页面添加书签。

为此,我创建了一个按钮弹出窗口,单击该按钮弹出窗口时会显示用于管理书签列表的UI。当用户点击扩展程序的按钮时,我想将正在查看的页面的URL传递给弹出窗口,以便我可以将其添加到书签列表中。我的问题是我不知道如何将URL传递给弹出窗口。有人能指出我正确的方向吗?

以下代码段是代码的简化版本,用于演示我的内容:

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>

1 个答案:

答案 0 :(得分:3)

这里的问题是scope。弹出窗口运行的范围无权访问正在查看的页面的URL;因此,要获取弹出范围的URL,弹出代码必须通过messaging从另一个范围请求信息。

执行此操作的最简单方法是,弹出窗口将消息发送到活动选项卡(Extension Page Scope),请求其显示的页面的URL。您可以按照以下方式实现此目的,我将让您执行将书签添加到列表中的代码。

<强> 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
  }
}
...

[披露:我是Crossrider员工]

相关问题