![](/img/trans.png)
[英]After clicking a link and loading a new page how can I then run a function?
[英]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.