Can't get Chrome Context Menu item to show on

2019-08-03 16:45发布

I have a Chrome extension that opens a KML/KMZ file in Google Maps. The extension is triggered when the user right-clicks a link to the KML document. But the context menu does not appear. It uses a background script. Here is the manifest.json:

{
  "manifest_version": 2,
  "name": "KML/KMZ Viewer",
  "version": "1.0.0",
  "description": "Can be used to view KML/KMZ Files.",
  "icons": {
    "19": "tiny.jpg",
    "24": "icon.png",
    "128": "image.png"
  },
  "permissions": [
    "tabs",
    "contextMenus",
    "activeTab",
    "background"
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

Here is the background.js:

// Set up context menu at install time.
chrome.runtime.onInstalled.addListener(function() {
    menuCreate();
    console.log('Issued function');
});

// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);

// The onClicked callback function.
function onClickHandler(info, tab) {
    var url = info.selectionText;
    openWin(url);
};

function openWin(kml) {
    chrome.windows.create({"url":"http://www.nearby.org.uk/google/fake-kmlgadget.html?    up_kml_url="+kml+"&up_view_mode=earth&up_lat=&up_lng=&up_zoom=&up_earth_2d_fallback=1&up_earth_fly_from_space=1&up_earth_show_nav_controls=1&up_earth_show_buildings=1&up_earth_show_terrain=1&up_earth_show_roads=1&up_earth_show_borders=1&up_earth_sphere=earth&up_maps_streetview=1&up_maps_default_type=hybrid"});
}

function menuCreate() {
    chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]});
    console.log('Function ran');
}

Yet when I right-click on a link to a KML or KMZ file, the context menu doesn't show. According to the JavaScript console, the functions ran. This is what the console outputs when I run chrome.contextMenus.create({"title": "Open KML/KMZ", "contexts": ["link"], "id": "kmlopen", "targetUrlPatterns": ["*.kml", "*.kmz"]}); manually under _generated_background_page.html I get the kmlopen, the id of the menu item. What am I doing wrong? The openWin(/*some url*/); function works fine.

1条回答
做自己的国王
2楼-- · 2019-08-03 16:57

Wrong pattern.

The patterns follow the standard Match pattern format.

So you should use the patterns

"targetUrlPatterns": ["*://*/*.kml", "*://*/*.kmz"]

However, be mindful of query strings.

查看更多
登录 后发表回答