如何从调用扩展程序的选项卡中轻松提取来源和特定参数?
如果当前 URL 是:
https://base.com/etc/etc?param1=123
我想得到两个变量 起源=“https://base.com” 和 参数 1 = "123"
理想情况下,如果有更多参数,这应该仍然有效,即 如果当前 URL 是 https://base.com/etc/etc?param1=123¶m2=234
我还是会得到 起源=“https://base.com” 和 参数 1 = "123"
我知道我可以使用类似的东西
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
但我正在慢慢学习 Javascript。这个函数会是什么样子?
最佳答案
The documentation for chrome.tabs.query说在回调 function (tabs)
中你会得到一个 Tab
数组。 Tab
有很多属性,其中之一是 url
。所以你可以这样做:
// Get the current active tab in the last focused Chrome window (before the popup showed)
// should return only ONE tab
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
if (!tabs[0]) { console.log('Could not get current tab'); return; }
// Now extract the information from the URL
let url = new URL(tabs[0].url);
let base = url.protocol + '//' + url.hostname;
let param1 = url.searchParams.get('param1');
console.log(base);
console.log(param1);
})
关于javascript - 获取 URL 来源和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47721056/