簡體   English   中英

單擊鏈接到新頁面后如何運行Javascript

[英]How to run Javascript after clicking link to new page

有什么方法可以使用Javascript打開鏈接,然后在新打開的網頁上運行代碼?

例如:

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

我已經使用chrome.tabs.executeScript打開新標簽頁並將Javascript插入其中,但是它似乎無法正常工作。

我嘗試使用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')" 
          });
        }
      )`
    });
  }
);

有什么解決辦法嗎?

為什么不只使用簡單的javascript方法來打開和控制瀏覽器彈出窗口和新標簽頁?

 //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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM