简体   繁体   中英

Manipulation of url from Google Chrome Extension - JavaScript

For my Google Chrome Extension, I have written the following code.

The aim is on button click the prefix '/crx/de/index.jsp' is appended to the end of the current url open. It's works to some extent, in that it appends the prefix however some unwanted extra prefix is also added. (See screenshot).

In this example, I had open: Google.com. You can see the prefix added and the unwated text highlighted in Blue.

See issue here - IMAGE

document.getElementById("crxde").addEventListener("click", handler_seven);  

function handler_seven() {
chrome.tabs.query({
currentWindow: true,
active: true
}, function(tab) {
var url = tab[0].url
var customParam = encodeURI('/crx/de/index.jsp');
var pathComponents = url.split('/');
var domain = pathComponents[2];
var newUrl = domain + customParam;

chrome.tabs.update(undefined, {
  url: newUrl
 });
});
};

Your URL doesn't have protocol:// so it's relative to the current page that contains the code which is evidently in the extension background script (it runs in a hidden background page) or in browser_action popup script (runs in the popup page). Such extension pages have a URL like chrome-extension://id/ so a relative URL specified in chrome.tabs.update is treated like a path to a resource inside the extension.

Use URL API and modern syntax:

chrome.tabs.query({
  currentWindow: true,
  active: true,
}, ([tab]) => {
  const url = new URL(tab.url);
  chrome.tabs.update({
    url: url.origin + '/crx/de/index.jsp',
  });
});

BTW There's no need to encode the path section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM