Metamask官方文档代码运行报错:非法字符串异常及未安装提示问题
MetaMask本地代码无法检测钱包的问题及解决
从MetaMask官方文档复制的启用钱包并显示账户的代码,本地直接打开HTML文件运行时无法正常工作。已安装MetaMask且在其他线上Web3站点可正常使用,但控制台输出SyntaxError: An invalid or illegal string was specified和DOMException错误,同时提示“MetaMask is not installed!”。
复制的代码
<!DOCTYPE html> <html> <head> <script> document.addEventListener("DOMContentLoaded", function() { const ethereumButton = document.querySelector(".enableEthereumButton"); const showAccount = document.querySelector(".showAccount"); if (!ethereumButton) { console.error("The element with class 'enableEthereumButton' was not found."); return; } ethereumButton.addEventListener("click", () => { getAccount(); }); async function getAccount() { // Check if MetaMask is installed if (typeof window.ethereum !== 'undefined') { try { // Request account access if needed const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); // Get the first account const account = accounts[0]; // Display the account showAccount.innerHTML = account; } catch (err) { if (err.code === 4001) { // EIP-1193 userRejectedRequest error console.log('Please connect to MetaMask.'); } else { console.error(err); } } } else { console.log('MetaMask is not installed!'); } } }); </script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title>Ethereum Account</title> </head> <body> <!-- Display a connect button and the current account --> <button class="enableEthereumButton">Enable Ethereum</button> <h2>Account: <span class="showAccount"></span></h2> </body> </html>
报错信息
SyntaxError: An invalid or illegal string was specified contentscript.js:1 DOMException: An invalid or illegal string was specified _postMessage file:///C:/Users/mirek/Downloads/pokus1/index.html:1 _write file:///C:/Users/mirek/Downloads/pokus1/index.html:1 _handshake file:///C:/Users/mirek/Downloads/pokus1/index.html:1 l file:///C:/Users/mirek/Downloads/pokus1/index.html:1 [1]</</< file:///C:/Users/mirek/Downloads/pokus1/index.html:1 [1]</< file:///C:/Users/mirek/Downloads/pokus1/index.html:1 [1]< file:///C:/Users/mirek/Downloads/pokus1/index.html:1 i file:///C:/Users/mirek/Downloads/pokus1/index.html:1 e file:///C:/Users/mirek/Downloads/pokus1/index.html:1 <anonymous> file:///C:/Users/mirek/Downloads/pokus1/index.html:1 MetaMask is not installed!
解决方法
- 核心原因:MetaMask扩展不会向
file://协议的本地页面注入window.ethereum对象,必须通过HTTP/HTTPS协议运行页面。 - 快速解决:
- 用本地HTTP服务器托管页面:
- Python 3环境:在代码目录执行
python -m http.server 8000 - Python 2环境:执行
python -m SimpleHTTPServer 8000
- Python 3环境:在代码目录执行
- 打开浏览器访问
http://localhost:8000,点击按钮即可正常连接MetaMask。
- 用本地HTTP服务器托管页面:
- 额外排查点:
- 确认MetaMask扩展已启用,浏览器未禁用第三方Cookie(部分隐私设置会阻止MetaMask注入)。
- 检查页面中
enableEthereumButton和showAccount类的元素是否存在,避免DOM选择失败。
内容的提问来源于stack exchange,提问作者Mirek
相关产品推荐
相关产品推荐

