首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Crossrider扩展平台

Crossrider扩展平台
EN

Stack Overflow用户
提问于 2014-08-03 15:33:24
回答 1查看 140关注 0票数 3

当用户单击扩展按钮时,我希望将正在查看的页面的URL传递给弹出窗口,以便将其添加到书签列表中。我的问题是我不知道如何将URL传递给弹出窗口。有谁能给我指个方向吗?

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

background.js:

代码语言:javascript
复制
appAPI.ready(function($) {
    appAPI.browserAction.setResourceIcon('images/icon.png');
    appAPI.browserAction.setPopup({
        resourcePath:'html/popup.html',
        height: 300,
        width: 300
    });
});

popup.html:

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

发布于 2014-08-03 19:29:35

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

最简单的方法是弹出窗口向活动选项卡(Extension Page Scope)发送一条消息,请求它所显示的页面的URL。您可以通过以下方式来实现这一点,我将让您自行编写将书签添加到列表中的代码。

extension.js

代码语言:javascript
复制
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

代码语言:javascript
复制
...
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员工

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25102601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档