点击按钮,如何在Chrome中获取当前网址 [英] How to get current URL in Chrome on click of the button

查看:705
本文介绍了点击按钮,如何在Chrome中获取当前网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个Chrome网址分享的Chrome扩展程序。现在我需要一个可以在浏览器中获取当前URL的代码。当我点击图标时,我想打开新标签( http://www.thatsite.com/sharer.php?u= +当前网址)。



我有两个文件:

manifest.json

<$ p $
name:在该网站上分享,
version:1,
browser_action:{
default_icon:icon.png
},
background:{
scripts:[background.js]
},
权限:[tabs],
manifest_version:2
}

和background.js

  chrome.browserAction.onClicked.addListener(function(activeTab){
var newURL = http://www.leegly.com/sharer.php?u=+<当前网址>;
chrome.tabs.create({url:newURL});
});


解决方案

chrome.browserAction.onClicked 事件发送,第一个参数保存有关当前选项卡的信息。



要获取当前选项卡的URL,请首先请求选项卡 activeTab 权限 >许可是不必要的,你可以省略它)。然后,获取URL就像阅读 tab.url 一样简单:

  chrome.browserAction.onClicked.addListener(function(tab){
var url_encoded_url = encodeURIComponent(tab.url);
var newURL =http://www.leegly.com/sharer.php? u =+ url_encoded_url;
chrome.tabs.create({url:newURL});
});

请注意,我使用 encodeURIComponent 。否则,如果当前URL包含&符(& ),则代码将失败。


I am making an chrome extension that shares url to one website. Now I need a code that can get current URL navigated in browser. When I click on icon I want to open new tab (http://www.thatsite.com/sharer.php?u= + current URL).

I have two files:

manifest.json

{
    "name": "Share on that site",
    "version": "1",
    "browser_action": {
        "default_icon": "icon.png"
    },
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["tabs"],
    "manifest_version": 2
}

and background.js

chrome.browserAction.onClicked.addListener(function(activeTab){
    var newURL = "http://www.leegly.com/sharer.php?u=" + <current URL here>;
    chrome.tabs.create({ url: newURL });
});

解决方案

When the chrome.browserAction.onClicked event is dispatched, the first argument holds information about the current tab.

To get the URL of the current tab, first request the activeTab permission in the manifest file (the tabs permission is unnecessary, you can omit it). Then, getting the URL is as simple as reading tab.url:

chrome.browserAction.onClicked.addListener(function(tab) {
    var url_encoded_url = encodeURIComponent(tab.url);
    var newURL = "http://www.leegly.com/sharer.php?u=" + url_encoded_url;
    chrome.tabs.create({ url: newURL });
});

Note that I've used encodeURIComponent. Without this, your code will fail if the current URL contains an ampersand (&).

这篇关于点击按钮,如何在Chrome中获取当前网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆