Reputation: 3802
I am trying to make a chrome button that allows a user to save their current URL. Later I will want to send that url to a website's database when they log back in, but that is beyond my current task.
The functionality that I want can be summed up in this image:
I found this question asked at the URL below, but the rules for chrome extensions have changed and that code no longer works. Get URL and save it | Chrome Extension
One comment says: "As of manifest_version 2, the above code will not work. All Scripts should be placed in a separate file & then include it on the main html. New version clearly states that Inline scripts and event handlers disallowed. "
I couldn't figure out how to implement what this person suggested.
What I have so far:
popup.hmtl
<html>
<body>
<p id="currentLink">Loading ...</p>
<hr />
<ul id="savedLinks"></ul>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
chrome.tabs.query({'active': true}, function (tabs) {
var url = tabs[0].url;
});
manifest:
{
"name": "URL Saver",
"version": "1.1",
"description": "A browser action that saves the url of the current open tab",
"permissions": [
"tabs"
],
"browser_action": {
"default_title": "URL CATCHER",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2,
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
Now, if I click the button, I just get a "Loading ... _______" message
Upvotes: 1
Views: 4146
Reputation: 36
Your Javascript isn't actually doing anything apart from storing the value of tabs[0].url in the variable url. I suspect you are trying to use the variable "url" outside the scope of the anonymous function. This will not work as you have declared the var inside the callback.
Your next port of call might have been declaring url outside of the callback and assigning the variable inside, this also will not work as the function is asynchronous. Meaning by the time you have tried to access the variable, it is not set. See the comment I replied to yours with for a good post detailing this.
Inside your manifest.json, make sure you include a permission for 'tabs' as follows
"permissions": [
"tabs"
],
and you can access it with
var getTab = function(tab){
console.log(tab);
};
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
getTab(tabs[0]);
});
Upvotes: 1