Chrome扩展background.js中window.open使用_self无效问题求助
_self Doesn't Work in Background.js (And How to Fix It) Hey there! Let's break down why your window.open("_self") works in your content script but fails in the background script, and get this sorted for you.
The Root Cause
Your detectclicks.js runs as a content script—it’s injected directly into the active tab’s webpage context. When you call window.open("_self") here, you’re targeting the current tab’s window exactly what you want, so it behaves as expected.
But background.js runs in Chrome’s hidden background page—a separate, invisible page tied to your extension, not the user’s visible active tab. When you use window.open("_self") here, you’re trying to replace the content of this hidden background page, not the user’s tab. That’s why nothing happens—you can’t see the background page change! Using _blank works because it creates a new visible tab regardless of where the call originates.
The Fix: Use Chrome’s Tabs API
To update the user’s active tab from the background script, you need to leverage Chrome’s tabs API instead of window.open. Here’s how to adjust your code:
Modify Background.js
Replace your alarm listener with this code, which targets the active tab directly:chrome.alarms.onAlarm.addListener(function() { // Fetch the currently active tab in the user's window chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { if (tabs.length > 0) { // Update the tab's URL to your target site chrome.tabs.update(tabs[0].id, {url: "http://www.google.com"}); } }); });Update Manifest Permissions
Add thetabspermission to yourmanifest.jsonso your extension can access the tabs API. I also removedbackground.jsfrom your content scripts list—running the background script in every tab is redundant and can cause conflicts:{ "name": "Chrome-extension", "version": "1.0", "manifest_version": 2, "permissions": [ "alarms", "cookies", "tabs" ], // Added "tabs" permission "background": { "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["jquery1.7.2.js", "detectclicks.js"] // Removed background.js } ], "description": "Chrome-extension", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" } }
Quick Side Note on Popup.js
Your popup.js line chrome.extension.getBackgroundPage().timers[tabId] = new Date(); will throw an error because tabId isn’t defined. If you need to track timers per tab, you’ll want to fetch the active tab’s ID first using chrome.tabs.query (similar to the example above), but that’s a separate issue from your original question.
This should resolve your problem—now when the alarm triggers, it’ll update the user’s active tab instead of trying to modify the hidden background page.
内容的提问来源于stack exchange,提问作者Jedi the padavann

