[英]window.location.href does not change the URL on button click
I would like to start of by saying that I have little knowledge of writing code in any form but can read and understand, for the most part.首先我想说的是,我对以任何形式编写代码知之甚少,但大部分情况下可以阅读和理解。
I am trying to create a Chrome extention that will change part of the URL for the active tab ( effectively a find and replace ), and then load the newly changed URL in the same tab.我正在尝试创建一个 Chrome 扩展,它将更改活动选项卡的 URL 的一部分(实际上是查找和替换),然后在同一选项卡中加载新更改的 URL。 So far I have a popup with a separate button that shows up when clicking the extention icon, but I am unable to make this button work.
到目前为止,我有一个带有单独按钮的弹出窗口,单击扩展图标时会显示该按钮,但我无法使该按钮起作用。 While I have not given up on finding a solution on my own, I come to you for help again as I don't know what I am missing.
虽然我没有放弃自己寻找解决方案,但我不知道我错过了什么,我再次向您寻求帮助。
Right now nothing happens when clicking the button.现在单击按钮时没有任何反应。
Code:代码:
(background.js is empty) (background.js 为空)
manifest.json:清单.json:
{
"name": "Extention name",
"description": "Extention description",
"version": "1.0",
"author": "Author Name",
"manifest_version": 3,
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions": ["storage" , "nativeMessaging" , "notifications" , "tabs"],
"action": {
"default_popup": "popup.html"
}
}
popup.html:弹出窗口.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<button id="Change">Change</button>
<script src="language.js"></script>
</div>
</body>
</html>
language.js: (Courtesy of mplungjan) language.js:(由 mplungjan 提供)
window.addEventListener('load', function() {
let url = new URL(window.location.href);
const Change = document.getElementById('Change').click();
const replace = () => {
console.log(Change.textContent, url.pathname)
const isEnglish = url.pathname.indexOf('en-US') != -1;
const from = isEnglish ? 'en-US' : 'nb-NO';
const to = isEnglish ? 'nb-NO' : 'en-US';
url.pathname = url.pathname.replace(from, to)
// window.history.pushState('', '', url);
};
Change.addEventListener('click', replace);
replace();
});
Now the line Change.addEventListener('click', replace);
现在行
Change.addEventListener('click', replace);
throws the following error within chrome://extensions/:在 chrome://extensions/ 中抛出以下错误:
Any help is greatly appreciated.任何帮助是极大的赞赏。
function next() { window.open('https://stackoverflow.com/', '_self' ) } // we used '_self' to open the url int the same tab... If you want to open it in a seperate tab, then you can remove '_self' /// You can give any url 'https://stackoverflow.com/' is only for an example
<.DOCTYPE html> <html> <head> <link rel="stylesheet" href="button.css"> </head> <body> <button onclick="next()" id="Change">Change</button> <!---YOU CAN GIVE ANY NAME TO THE FUNCTION--> <script src="language.js"></script> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.