user9504869
user9504869

Reputation:

Chrome Extension: URL not opening in new tab

So, I am getting a dynamic URL which I want to open in new tab.

PS: I am currently writing this in content script. for example

  var newURL =  document.querySelectorAll("a")[lengthA].href

I want to open this in new tab. In javascript, We simple do window.open to open URL in new tab but it wasn't working, then I google the same and saw that in order to open URL in new tab, we need to do..

chrome.tabs.create({ url: newURL });

So I did the same i.e

  var newURL =  document.querySelectorAll("a")[lengthA].href
              chrome.tabs.create({ url: newURL });

But even that doesn't work. What am I doing wrong here?

Upvotes: 0

Views: 609

Answers (2)

user7624583
user7624583

Reputation:

I made plenty of extensions with the intention of what you are doing and I used this:

function MyFunc() {
  var win = window.open("https://www.google.com", '_blank');
  win.focus;
}

if you add an event listener like this

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById("MyButton").addEventListener("mousedown", MyFunc);
});

It should work perfectly

Upvotes: 1

Alwaysblue
Alwaysblue

Reputation: 11940

Content script don't have access to all chrome API's so you would need to send a message to an event page.

Inside your content Script do like this to send a message to your event page

chrome.runtime.sendMessage({otab: "sendx", xname: newURL});

Now in your event page, you need to receive message to open this.

chrome.runtime.onMessage.addListener(function(request, sender, senderResponse){
if (request.otab == "sendx") {
  chrome.tabs.create({url: request.xname });
  }
})

refer this document https://developer.chrome.com/extensions/content_scripts

Upvotes: 0

Related Questions