【问题标题】:Crossrider Extension PlatformCrossrider 扩展平台
【发布时间】:2014-08-03 07:33:23
【问题描述】:

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

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

以下sn-p是代码的简化版本,用于演示我所拥有的:

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>

【问题讨论】:

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


    【解决方案1】:

    这里的问题是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 的员工]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-20
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 2015-12-18
      • 2014-05-14
      相关资源
      最近更新 更多