Windows10/11命令行启动Chrome/Edge并向JS传参的方法
可以通过命令行启动Chrome/Edge并向JavaScript传递参数
下面是几种可行的实现方案:
1. URL查询参数传递(最简便)
直接把参数附加到目标页面的URL末尾,页面内的JavaScript可通过window.location.search解析获取参数。
命令行示例:
- Chrome:
chrome.exe "file:///C:/path/to/your/index.html?user=alice&msg=hello" - Edge:
msedge.exe "file:///C:/path/to/your/index.html?user=alice&msg=hello"
页面JavaScript解析代码:
const urlParams = new URLSearchParams(window.location.search); const username = urlParams.get('user'); // 得到"alice" const message = urlParams.get('msg'); // 得到"hello" console.log(username, message);
2. 本地临时文件传递(适合大内容)
如果要传递的字符串体积较大,可先写入本地临时文件,页面加载后通过JS读取文件内容:
- 命令行步骤(先写文件再启动浏览器):
echo "这是一段较长的需要传递的字符串内容" > C:/temp/transfer_data.txt chrome.exe "file:///C:/path/to/your/index.html" - 页面JS读取逻辑:
fetch('file:///C:/temp/transfer_data.txt') .then(res => res.text()) .then(data => { console.log('接收的内容:', data); // 读取完成后可删除临时文件 });
3. 自定义协议传递(进阶场景)
若不想参数暴露在URL中,可注册系统自定义协议(比如myapp://),通过协议触发页面并传递参数:
- 先在系统注册表中注册自定义协议(需管理员权限)
- 命令行调用示例:
chrome.exe "myapp://open?target=C:/path/to/index.html&data=custom_content" - 页面JS需监听导航事件,解析自定义协议中的参数内容
内容的提问来源于stack exchange,提问作者FDavidov
相关产品推荐
相关产品推荐

