当用户单击扩展按钮时,我希望将正在查看的页面的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>发布于 2014-08-03 19:29:35
这里的问题是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员工
https://stackoverflow.com/questions/25102601
复制相似问题