任何人都可以帮我把我的三个片段放到一个可用的脚本中。
1) Get active window URL
2) Strip URL for ID only
3) Concatenate API request to include ID from URL
以下内容返回我当前的窗口网址。
chrome.tabs.query({active: true, currentWindow: true},
function(tabs) {
var tabURL = tabs[0].url;
console.log(tabURL);
});
实施例.... https://myapi.com/users/PLLFFR6
function test() {
var urlID = tabURL.split("/");
urlID = urlID[urlID.length-1];
}
这会拆分https://myapi.com/users/PLLFFR6 并仅返回" PLLFFR6"
var authorizationToken = "xxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/' + urlID + '?include%5B%5D=contact_methods&include%5B%5D=teams');
基于此示例,myapiRequest应该=
**/users/PLLFFR6?include%5B%5D=contact_methods&include%5B%5D=teams**
答案 0 :(得分:2)
这样的事情应该有效:
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
function apiRequest(endpoint, options) {
return new Promise(function (resolve) {
$.ajax(
$.extend({}, {
type: 'GET',
dataType: 'json',
success: function(data) {
resolve(data)
},
url: 'https://api.website.com/' + endpoint,
headers: {
Authorization: 'Token token='+authToken,
Accept: 'application/vnd.myapi+json;version=2'
}
}, options)
)
})
}
/* example usage */
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return apiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
})
请注意,由于您使用的是chrome.tabs
,因此这只能用作浏览器中的Chrome扩展程序而不是。您还需要加载jQuery(使用$.ajax
和$.extend
)。