accessing the current html page from chrome extension

后端 未结 4 1693
一向
一向 2021-01-01 19:28

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

相关标签:
4条回答
  • 2021-01-01 19:45

    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
    0 讨论(0)
  • 2021-01-01 19:50

    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"})
    });
    
    0 讨论(0)
  • 2021-01-01 19:59

    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

    0 讨论(0)
  • 2021-01-01 20:00

    You can use the tabs module:

    chrome.tabs.getCurrent(function(tab) {
        alert(tab.title);
    });
    
    0 讨论(0)
提交回复
热议问题