I have a simple Chrome extension that adds a browser action. When the extension's popup is opened, it needs to access the current tab's URL. Since it doesn't need access to all the tabs, I just have the activeTab
permission specified in the manifest:
{
"manifest_version": 2,
"name": "RequireJS Test",
"version": "0.0.1",
"description": "Test RequireJS and the activeTab permission.",
"permissions": [
"activeTab"
],
"browser_action": {
"default_popup": "popup.html"
},
"web_accessible_resources": [
"js/*",
"html/*",
"css/*",
"img/*"
]
}
In theory, that should give the popup access to the active tab's URL, but the URL is not returned when I query the tabs from within a require()
call in the popup's main.js
file:
require([], function() {
chrome.tabs.query({"active": true, "lastFocusedWindow": true}, function (tabs) {
var url = tabs[0].url;
console.log("URL from main.js", url);
});
console.log("URL from global var accessed in main.js", tabURL);
});
The console shows undefined
for the URL. However, if I make the same call from a plain .js file that doesn't use require()
, it works fine:
chrome.tabs.query({"active": true, "lastFocusedWindow": true}, function (tabs) {
tabURL = tabs[0].url;
console.log("URL from get-url.js", tabURL);
});
That displays the correct URL, and I can access that global tabURL
inside the require()
call just fine. When I right-click the browser button and inspect the popup, the console output looks like this:
URL from get-url.js http://stackoverflow.com/questions/ask
URL from global var accessed in main.js http://stackoverflow.com/questions/ask
URL from main.js undefined
Even stranger is that I've sometimes seen the URL available from within that call to chrome.tabs.query()
inside the require()
call. But mostly it doesn't work. Something about how RequireJS loads scripts seems to confuse Chrome and take away the URL access for the loaded script. This is in Chrome 40 on Windows.
Obviously, the workaround is to grab the URL in a separate script and store it in a variable, but that feels a bit kludgy. I'd like to see if there's a proper way of getting this to work with RequireJS.
The full plugin source is here if anyone wants to test it on their machine: https://github.com/fwextensions/requirejs-url-test
Edit
As Rob W. explains below, this actually has nothing to do with RequireJS. The only reason that the code in my get-url.js
file above returned the correct URL was that it happened to run before the devtools window opened. If I change that file to this:
setTimeout(function() {
chrome.tabs.query({"active": true, "lastFocusedWindow": true}, function (tabs) {
tabURL = tabs[0].url;
console.log("URL from get-url.js", tabURL);
});
}, 5000);
Then it runs after the devtools window is open and fails as well. RequireJS isn't the culprit.