accessing the current html page from chrome extension

孤者浪人 提交于 2019-12-18 14:52:01

问题


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 it 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?


回答1:


You can use the tabs module:

chrome.tabs.getCurrent(function(tab) {
    alert(tab.title);
});



回答2:


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



回答3:


For what your doing all you need to do is this

chrome.tabs.executeScript({
    code: 'alert(document.title)'
})

The chrome.tabs.executeScript api 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




回答4:


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"})
});


来源:https://stackoverflow.com/questions/7697001/accessing-the-current-html-page-from-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!