0

Is there any way to open a link using Javascript, and then run code on the newly opened webpage?

For example:

document.querySelector('a').click();
// execute code on new page here...

I have used chrome.tabs.executeScript to open new tabs and insert Javascript into them, but it doesn't appear to work.

Example of what I am trying to accomplish using chrome.tabs.executeScript:

chrome.tabs.create(
  {
    url: "https://www.example.com/",
    active: true
  },
  function(tab) {
    chrome.tabs.executeScript(tab.id, {
      code: `chrome.tabs.create(
        {
          url: "https://www.google.com/",
          active: true
        },
        function(tab) {
          chrome.tabs.executeScript(tab.id, { 
            code: "console.log('hello world')" 
          });
        }
      )`
    });
  }
);

Is there any solution to this problem?

max
  • 147
  • 1
  • 7
  • Overall it should work but the problem here is that you're running the second chrome.tabs.create as a content script, and chrome.tabs is not available for content scripts - if you open [**proper** devtools](/a/38920982) you will see the error. I'm not sure what you've tried to achieve by that so I just guess you don't need about a half of the code, what you need probably is chrome.tabs.create({......}, tab => chrome.tabs.executeScript(tab.id, {code: 'console.log'})) – wOxxOm Aug 28 '19 at 04:15

1 Answers1

-1

Why do not you just use the simple javascript way to open and control browser popup and new tabs ?

//This code doesn't work on the snippet please copy and past it on a real test file to see the magic !

document.addEventListener("click", function(e){
  e=(e||window.event);
  e.preventDefault();
  const path=e.path;
  for(var i=0;i<path.length-4;i++){
    if( path[i].tagName=="A" ){
      const href=path[i].getAttribute("href");
      const newTab=window.open(href, "_blank");
        
      //Here you can add any function to your new tab just like 
      
      newTab.alert("This alert must be opened on the new tab :) ");
      
      //You can also add some js variables through the window object just like
      
      newTab.myNameIs="Adnane Ar";
      
      
    } 
  }
});
<a href="https://www.google.com">New Tab</a>
Adnane Ar
  • 683
  • 7
  • 11
  • Because it won't work for cross-origin URLs and such popups can be blocked by the browser. – wOxxOm Aug 28 '19 at 04:19
  • Since the original code runs inside a chrome-extension:// page there will be no same-domain pages here so the answer has no value in this case. – wOxxOm Aug 28 '19 at 10:33
  • I got your point, and you are right! I thought that he needs only a function to open and control new windows without using the **chrome-extension** – Adnane Ar Aug 28 '19 at 16:33