// content.js
export function waitSec(timeInSec, func) {
timeInSec = timeInSec * 1000
setTimeout(function () {
console.log('Waiting ' + timeInSec + ' seconds');
func()
}, timeInSec);
}
这将返回:未捕获的语法错误:无法在模块外部使用 import 语句
已经尝试过:重命名,添加“导出”
附注如果有更好的方法在 js chrome 扩展脚本中等待,请告诉我!
如果需要的话,这是完整的脚本:
// content.js
export function waitSec(timeInSecd, func) {
timeInSec = timeInSec * 1000
setTimeout(function () {
console.log('Waiting ' + timeInSec + ' seconds');
func()
}, timeInSec);
}
// Handles button and has to be the same in popup.js and content.js until I find a better solution
function sharedTempHandleButton() {
alert("Test");
const buttonToClick = document.querySelector('.zp_FVbJk');
if (buttonToClick) {
waitSec(1, () => { buttonToClick.click(); })
} else {
console.error('Button not found using the provided CSS selector');
alert("Button not found using the provided CSS selector")
}
}
// Create a new header element
const header = document.createElement('h4');
header.textContent = 'Artemis enabled';
const lineBreak = document.createElement('br');
const startButton = document.createElement("button");
startButton.textContent = "Start";
startButton.id = "startButton";
// Prepend the header to the body
document.body.prepend(header, lineBreak, startButton);
startButton = document.getElementById("startButton")
startButton.addEventListener("click", () => {
sharedTempHandleButton()
})
您遇到的错误“未捕获的语法错误:无法在模块外部使用导入语句”表明您正在尝试在未被识别为模块的脚本中使用导入语句。
import 语句是 ES6 模块特性,只能在被视为模块的文件中使用。要使用导入和导出语句,您需要将 type="module" 属性添加到 HTML 文件中的脚本标记中。
以下是修改脚本的方法:
<!-- Add type="module" to the script tag -->
<script type="module" src="your-script.js"></script>
在您的 JavaScript 文件 (your-script.js) 中,您可以使用导入和导出:
export function waitSec(timeInSec, func) {
const timeInMillis = timeInSec * 1000;
setTimeout(function () {
console.log('Waiting ' + timeInSec + ' seconds');
func();
}, timeInMillis);
}
确保在脚本标签的 src 属性中使用正确的脚本路径。
此外,请注意,在您的 waitSec 函数中,我更正了几个拼写错误:
将 timeInSecd 更改为 timeInSec。 将 timeInSec = timeInSec * 1000 更改为 const timeInMillis = timeInSec * 1000。 确保将这些更改应用到您的代码中。进行这些调整后,您的脚本应该按预期工作。