我正在使用Chrome扩展程序,我们可以在其中共享标签或窗口的当前网址,该网址处于有效状态。我在javascript中获取当前活动的URL时遇到了一些麻烦。
尝试了
var current_url = window.location.host;
, var current_url = window.location.hostname;
, var current_url = window.location.href;
and var current_url = document.location.href;
这是URL传递函数的代码:(background.js):
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.message=='openurl'){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var tab = tabs[0];
var page_url = tab.url;
wayback_url = message.wayback_url;
var pattern = /https:\/\/web\.archive\.org\/web\/(.+?)\//g;
url = page_url.replace(pattern, "");
open_url = wayback_url+encodeURI(url);
if(message.method!='save'){
status = wmAvailabilityCheck(page_url,
function(){ chrome.tabs.create({ url: open_url});
sendResponse({status:true});
},
function(){
//alert("URL not found in wayback archives!");
sendResponse({status:false});
});
}
else{
chrome.tabs.create({ url: open_url});
}
});
}
else if(message.message=='geturl') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0];
var page_url = tab.url;
if(isValidSnapshotUrl(page_url)){
sendResponse({url: page_url});
}
});
}
return true;
});
popup.js的代码:
function get_alexa_info(){
chrome.runtime.sendMessage({message: "geturl" }, function(response) {
shareon_facebook(response.url);
shareon_twitter(response.url);
shareon_googleplus(response.url);
}
function shareon_facebook(url)
{
var current_url = url;
var fbshr_url = "https://www.facebook.com/sharer/sharer.php?u="
window.open(fbshr_url + current_url , 'newwindow', 'width=500, height=400');
}
function shareon_twitter(current_url)
{
var twitshr_url = "https://twitter.com/home?status=";
window.open(twitshr_url + current_url , 'newwindow', 'width=500, height=400');
}
function shareon_googleplus(url)
{
var gplusshr_url = "https://plus.google.com/share?url=";
window.open(gplusshr_url + url , 'newwindow', 'width=500, height=400');
}
由于其他原因,我无法提供有关此扩展程序的更多信息。
答案 0 :(得分:0)
如果您想获取活动标签的网址,请尝试以下操作:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function
(tabs) {
var url = tabs[0].url;
document.getElementById("host").innerHTML = url;
});
然后你可以在这样的html文件中显示它:
<div id="host"></div>