accessing the current html page from chrome extension
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: alert(document.title)
, I'm not getting i开发者_运维技巧t because the document object doesn't belong to the page but to the extension script (is it correct?)
how do i get the right document object?
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
.
See also:
- Developer's guide
- Content scripts
- Background pages
You can use the tabs module:
chrome.tabs.getCurrent(function(tab) {
alert(tab.title);
});
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
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"})
});
精彩评论