我正在构建一个简单的 Chrome 扩展程序,用户选择一个按钮并打开一个新的浏览器页面到随机选择的网站(例如 Stumble Upon 或 Cloudhiker)。但是,单击时,会打开一个新的浏览器页面,但它表示该页面特定于扩展程序,并且预期的 URL 前面带有 Chrome 扩展程序数据。例如:chrome-extension://hflifofppgknepfodmmkohenjknmendb/www.bing.com
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stumble Upon Clone</title>
<link rel="stylesheet" href="style.css" />
<script src="scripts.js"></script>
</head>
<body></body>
</html>
body {
background-color: black;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 50vh;
min-width: 200px;
border-radius: 10px;
}
h1 {
color: grey;
}
document.addEventListener('DOMContentLoaded', () => {
const title = document.createElement('h1');
title.innerText = 'Welcome to the Stumble Upon Clone!';
document.querySelector('body').appendChild(title);
const btnStumble = document.createElement('button');
btnStumble.setAttribute('class', 'btnStumble');
btnStumble.innerText = "Let's Stumble!";
document.querySelector('body').appendChild(btnStumble);
btnStumble.addEventListener('click', () => {
const selection = randomSite();
console.log(selection);
window.open(selection);
});
});
const sites = ['www.google.com', 'www.yahoo.com', 'www.bing.com'];
const randomSite = () => {
const roll = Math.floor(Math.random() * 3);
const choice = sites[roll];
return choice;
};
randomSite(sites);
randomSite(sites);
randomSite(sites);
{
"manifest_version": 3,
"name": "Stumble Upon Clone",
"version": "1.0.0",
"description": "My version of the old Stumble Upon website",
"action": {
"default_popup": "index.html"
},
"icons": {
"48": "img/cloud.png"
}
}
我尝试将 window.open 更改为 document.open,但这没有帮助。我不知道此时还能做什么。感谢您提供的任何帮助和见解!
简短的答案是:将“https://”或“http://”添加到
sites
中的 URL,它应该可以工作。
稍长的答案是:如果您调用
window.open()
,您可以提供相对或绝对 URL。如果要提供绝对 URL,则需要添加 URL 方案(即“https://”或“http://”),以便将其识别为绝对 URL。如果没有,window.open()
假定给定的 URL 是相对的,并将相对于当前 URL 添加它,当前 URL 是您从扩展程序的弹出页面打开它时的扩展程序的 URL。