I\'m new to chrome extensions.
I would like to create a simple chrome extension that popup an alert with the title of the current html page.
when I\'m performing: ale
Content scripts are the easiest way to go:
Expand your manifest file with this code:
...
"content_scripts": [
{
"matches": ["http://urlhere/*"],
"js": ["contentscript.js"]
}
],
...
Content script (automatically executed on each page as mentioned at matches
at the manifest file):
alert(document.title)
The advantage of using content scripts over chrome.extension.*
methods is that your extension doesn't require scary permissions, such as tabs
.
I use this extension to do a similar thing:
main.js:
(function(){window.prompt('Page title:', document.title)})()
manifest.json:
{
"background": {"scripts": ["background.js"]},
"browser_action": {
"default_title": "popup_title"
},
"name": "popup_title",
"description": "Display the page title for copying",
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"version": "1.0",
"manifest_version": 2
}
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {file: "main.js"})
});
For what you're doing all you need to do is this
chrome.tabs.executeScript({
code: 'alert(document.title)'
})
Chrome.tabs.executeScript allows you to run JavaScript in the current page instead of in the extension. So this works just fine but if you want to use the name of the page later in a more complex extension than I would just do what pimvdb did
You can use the tabs module:
chrome.tabs.getCurrent(function(tab) {
alert(tab.title);
});