【发布时间】:2013-11-16 14:31:13
【问题描述】:
我得到的是上次访问的 url,而不是当前的。 (当我访问 site.com 并随后访问 site2.com 时,我得到的网址是“site.com”,在我刷新 site2.com 后,我得到了正确的网址。
根据这里的答案:
Google Chrome Extension get page information
Display current URL in a chrome extension
我想出了这个代码:
manifest.json
{
"manifest_version": 2,
"browser_action": {
"default_popup": "action.html"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs",
"unlimitedStorage",
]
}
content.js
chrome.extension.sendRequest({method: "getUrl"}, function(response) {
console.log(response.data);
});
background.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.method == "getUrl") {
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
currentUrl = tabs[0].url;
});
sendResponse({data: currentUrl});
}
else
sendResponse({}); // snub them.
});
我还尝试将此代码直接放在 content.js 中,但在 background.js 中出现错误,并且 URL 设置为 chrome://extensions/。
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
currentUrl = tabs[0].url;
});
这样做的正确方法是什么?
【问题讨论】:
-
你试过强制你的内容脚本在document loads之后运行吗?
-
也发布您的清单。
-
@hiattp 我添加了
"run_at": "document_end",但没有任何改变。 -
为什么要使用内容脚本?仅背景页面就足以达到此目的。此外,在使用背景/事件页面时,您可以看到所有 URL 的导航,包括
chrome://URL。查看chrome.webNavigationAPI,尤其是onCommitted事件。