bs7280
bs7280

Reputation: 1094

chrome extension - get tab url from background page without popup

I would like to be able to get the current url of the tab the user is on, without having forcing the user to click on the popup button. I have gotten a script to work out where the user clicks on the popup icon and everything works as it is supposed to, but to try and accomplish my current goal (to do so without pressing the button) I coppied and pasted the code into a background page, and got no results. My guess was that I needed some active listener or something along those lines.

This is the javascript that I got to work with the popup button

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
  chrome.tabs.getSelected(null, function(tab) {
        //doing stuff with the url
  });
}
</script>

Upvotes: 4

Views: 6657

Answers (3)

Jerry Z.
Jerry Z.

Reputation: 2051

another approach: get it from content script and send it to background page:

url = window.location.href;

    chrome.runtime.sendMessage({greeting: url}, function(response) {
    });

in background.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
        var url=message.greeting;
}

Upvotes: 3

jamesmortensen
jamesmortensen

Reputation: 34038

According to the docs for Packaged Apps, which may or may not be the same for extensions, you use the onLaunched event from the chrome.app API's to run code when the app launches:

// start doing something when the app first loads....
chrome.app.runtime.onLaunched.addListener(function() {
    // all your monitoring code will go here

});

Note that, if building an extension, and your extensions should start listening as soon as the browser loads, you may not need to declare an "onLaunched" listener.

Additionally, you'll need to monitor for changes to the active tab, assuming you want to always know the url that the user is on in the currently active tab. The Chrome Tabs API contains a lot of information that will help you work with tabs from an extension, for instance, here is the code to monitor for changes to the active tab:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    console.info("This is the url of the tab = " + changeInfo.url);
    // do stuff with that url here....
});

If the user changes the url in the active tab, this handler will monitor for that change:

chrome.tabs.onActivated.addListener(function(activeInfo) { .. }

However, the documentation for onActivated says the following:

Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.

Thus, you'll more than likely just use the onUpdated event example.

When you get to a point in the background page where you encounter a page you wish to inject JavaScript into. For instance, to change the background color of the page using JavaScript, you use the following code:

chrome.tabs.executeScript(null,
                           {code:"document.body.bgColor='red'"});

Remember, your background page cannot directly run JavaScript or manipulate the DOM of a web page; thus, you'll need to inject code in this manner, which would include injecting things like jQuery and other resources that you would need.

Don't forget to allow tabs permissions and the background page in your manifest.json:

/* in manifest.json */
"permissions": [
  "tabs", "http://*/*"
],
"background": {
  "scripts": ["background.js"]
},

To inject jQuery into the page, you'd basically write code that builds a script element, and then you would inject that into the page:

chrome.tabs.executeScript(null,
    {code:
        "var script = document.createElement('script');" +
        "script.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');" +
        "script.setAttribute('type','text/javascript');" +
        "document.getElementsByTagName('head')[0].appendChild(script);"

   }
);

The code in double-quotes doesn't run in your background page. Instead, it runs when injected onto the page in the tab. I use single quotes for content inside the double quotes so the parser doesn't get confused and throw string literal errors.

Note that there may be a better, cleaner way to inject such code onto the page, but for small, minor injections, this is sufficient.

Keep in mind that, if jQuery is already injected in the page, you may run into conflicts.

Upvotes: 5

OnenOnlyWalter
OnenOnlyWalter

Reputation: 437

In your Chrome Extension, you will likely need a file running in the background. Check out this Developer article on creating a page called background.js

This will allow you to place code in your file that persists while the extension is enabled.

Upvotes: -3

Related Questions