office-admin-debugging时每次都提示localhost loopback

最近在做一个excel插件,使用新的office.js技术栈而不是VisualStudio Tools for Office

问题

开发时需要用到office-addin-debugging,

1
2
3
4
$ office-addin-debugging start manifest.xml desktop --app excel
Debugging is being started...
App type: desktop
? Allow localhost loopback for Microsoft Edge WebView? (Y/n)

但每次启动都会提示而不是会记住选择。

查找原因

看了下源码,问题出现的原因其实出奇的简单。

我们一步步的看吧。

office-addin-debugging命令

office-addin-debugging调用的是node_modules\.bin\下的可执行文件,在windwos下是office-addin-debugging.cmd

1
node  "%~dp0\..\office-addin-debugging\cli.js" %* 

cli.ts ->
commands.ts@start ->
start.ts@startDebugging ->
office-addin-dev-settings@ensureLoopbackIsEnabled

1
2
3
4
5
// enable loopback for Edge
if (isWindowsPlatform && parseInt(os.release(), 10) === 10) {
const name = isDesktopAppType ? "EdgeWebView" : "EdgeWebBrowser";
await devSettings.ensureLoopbackIsEnabled(name); // <- 为edge开启loopback
}

office-addin-dev-settings

appcontainer.ts@ensureLoopbackIsEnabled ->
appcontainer.ts@isLoopbackExemptionForAppcontainer

1
2
3
4
5
6
7
8
9
10
11
12
13
return new Promise((resolve, reject) => {
const command = `CheckNetIsolation.exe LoopbackExempt -s`;

childProcess.exec(command, (error, stdout) => {
if (error) {
reject(stdout);
} else {
const expr = new RegExp(`Name: ${name}`, "i"); // <- 判断是否已经在豁免列表
const found: boolean = expr.test(stdout);
resolve(found);
}
});
});

stdout

stdout的内容会根据console code page变化,并不一定是英文的。

如果我们的windows显示语言为中文,活跃代码页为936(gb2312)

1
2
$ chcp
活动代码页: 936

此时上面的命令行CheckNetIsolation.exe LoopbackExempt -s输出的stout为

1
2
3
4
5
6
7
$ CheckNetIsolation.exe LoopbackExempt -s

列出环回免除的 AppContainer

[1] -----------------------------------------------------------------
名称: microsoft.win32webviewhost_cw5n1h2txyewy
SID: S-1-15-2-1310292540-1029022339-4008023048-2190398717-53961996-4257829345-603366646

注意到那个汉字名称:了吗?此时的匹配就会无效RegExp(`Name: ${name}`, "i")

解决方案

方案一

直接改源码,只需将RegExp(`Name: ${name}`, "i")改为RegExp(`${name}`, "i")就完事。

方案二

不改源码,让childProcess.exec(command,的stdout为英文。

方案二可能会增加开发的前置工作,故直接使用方案一。只需要修改excel插件工程下的node_modules\office-addin-dev-settings\lib\appcontainer.js,就对当前工程一直用效。