Open a local .html on extension mouse click

≯℡__Kan透↙ 提交于 2020-02-23 05:36:16

问题


I'm creating my first chrome extension. When the extension icon is clicked, I wish that chrome will open a new tab, and open there a local .html page I have created.

Following the instructions on Google's documentation, I have created the following:

manisfest.json

{
  "manifest_version": 2,

  "name": "Notes",
  "version": "1.0",

  "browser_action": {
    "default_icon": "ninjaicon.png",
    "default_popup": "notes.html"
},

  "background": {
    "scripts": ["background.js"]
},

  "permissions": [
    "tabs"
 ]
}

background.js

chrome.browserAction.onClicked.addListener(function(activeTab){
  chrome.tabs.create({'url': chrome.extension.getURL('notes.html')}, function(tab)
  });
});

When I press my extensions icon, there is a popup with "notes.html" content, but no new tab is opened like I wished.

How am I suppose to do it correctly? been looking up on a lot of solutions here but non worked. I just wish to create an extension that when clicked opens a new tab with a local web application.

Thanks for the answers.


回答1:


For this to work, the notes.html should be in your extension's root directory.

Remove the default_popup from the manifest file as

The onClicked event is fired when a browser action icon is clicked but this event will not fire if the browser action has a popup as it overrides this event.

This is mentioned in the documentation here, scroll to the last to read the same.

Also, have you tried to see your background page's console. I see the code you have written is wrong. There is no opening brace in your chrome.tabs.create callback function. Fix it if you want to add code to your callback function, if not you can simply write like this:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.create({url: chrome.extension.getURL('notes.html')});
});

I hope this helps.




回答2:


there is two way to open your local html page by the browser action.

1. As a popup

manifest.json

"browser_action":   {
                            "default_icon"  :   "128.png",
                            "default_popup" :   "localPage.html",
                            "default_title" :   "localPage title"
                        }

2. As a normal page in chrome browser

manifest.json

"background": {
        "scripts": ["background.js"]
    },

background.js

chrome.browserAction.onClicked.addListener(function () {
    chrome.tabs.create({ url: chrome.runtime.getURL("localpage.html") });
});


来源:https://stackoverflow.com/questions/35846565/open-a-local-html-on-extension-mouse-click

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