如何合并脚本实现点击按钮打开300*250新窗口并在其中打开三个标签页?
Solution: Combine Window Opening and Tab Creation
Alright, I've put together a combined script that does exactly what you're asking for—clicking a button will first open a 300×250 new window, then open your 3 links as new tabs inside that same window. Here's the full working code:
<button id="openLinksBtn">Open Links</button> <script> document.getElementById('openLinksBtn').addEventListener('click', function() { // Step 1: Open the initial 300x250 window (using a blank page as the starting point) const targetWindow = window.open( '', 'CustomWindow', 'width=300,height=250,resizable=yes' ); // Check if the window was blocked by a popup blocker if (!targetWindow) { alert('Popup blocked! Please allow popups for this site to use this feature.'); return; } // Step 2: Define your 3 target links const links = [ 'https://your-first-link-url.com', 'https://your-second-link-url.com', 'https://your-third-link-url.com' ]; // Open each link as a new tab inside the target window links.forEach(link => { targetWindow.open(link, '_blank'); }); }); </script>
Key Details Breakdown:
- Saving the Window Reference: When we call
window.open()initially, we store the returned window object intargetWindow. This is the critical piece that lets us direct all subsequent tab openings to that specific window, not random new windows. - Opening Tabs in the Target Window: Using
targetWindow.open(link, '_blank')tells the browser to open each link as a new tab inside the window we just created, instead of spawning entirely separate windows. - Popup Blocker Handling: Browsers often block popups that aren't triggered by direct user interaction. We added a check to alert the user if the initial window was blocked, so they can adjust their browser settings to allow it.
- Customizable Window Options: The third parameter in
window.open()includeswidth=300,height=250to match your required size. You can add extra options likemenubar=noorscrollbars=yesif you want to tweak the window's appearance further.
Just replace the sample URLs in the links array with your actual links, and you're ready to test it out!
内容的提问来源于stack exchange,提问作者Tyrange Denhops
相关产品推荐
相关产品推荐

