如何从同内网外部HTML页调用SharePoint 2010的openDialogSearch函数
好的,要实现这个需求,你得先搞清楚浏览器的同源策略限制——毕竟跨页调用脚本可不是随便就能做的,不过好在你是同一内网环境,有几种可行的方案:
方案1:通过嵌入iframe直接调用(同源场景推荐)
如果你的外部HTML页面和SharePoint站点协议、域名、端口完全一致(比如都是http://intranet.company.com:80),这是最直接的方法:
- 步骤:
- 在外部页面中添加一个隐藏的iframe,指向包含
openDialogSearch函数的SharePoint页面:<iframe id="spSearchFrame" src="http://你的SharePoint站点地址/包含函数的页面路径" style="display: none;"></iframe> - 等待iframe加载完成后,通过
contentWindow调用目标函数:document.getElementById('spSearchFrame').addEventListener('load', function() { // 传入你的资源URL调用函数 this.contentWindow.openDialogSearch('http://目标资源的URL'); }); - 注意:如果SharePoint需要身份验证,确保你的内网用户已经通过单点登录(比如NTLM认证),否则iframe会跳转到登录页,导致调用失败。
- 在外部页面中添加一个隐藏的iframe,指向包含
方案2:提取函数到独立JS文件(更可靠的长期方案)
如果你有权限修改SharePoint站点的内容,建议把页内的openDialogSearch函数移到独立的JS文件中,这样外部页面可以直接引用:
- 步骤:
- 在SharePoint站点中创建一个自定义JS文件(比如
sp-search-utils.js),把函数代码复制进去并挂载到全局对象:// 确保函数全局可访问 window.openDialogSearch = function(resourceUrl) { // 原函数的逻辑代码,比如调用SharePoint对话框 SP.UI.ModalDialog.showModalDialog({ url: resourceUrl, title: '搜索资源', width: 800, height: 600 }); }; - 在外部HTML页面中引用必要的SharePoint内置JS和自定义JS:
<!-- 先加载SharePoint依赖的核心脚本 --> <script src="http://你的SharePoint站点地址/_layouts/15/sp.js"></script> <script src="http://你的SharePoint站点地址/_layouts/15/sp.ui.dialog.js"></script> <!-- 引用自定义的函数文件 --> <script src="http://你的SharePoint站点地址/存放JS的路径/sp-search-utils.js"></script> - 等待SharePoint脚本加载完成后调用函数:
// 确保SP.js加载完成后再执行,避免依赖报错 ExecuteOrDelayUntilScriptLoaded(function() { openDialogSearch('http://目标资源的URL'); }, 'sp.js');
- 在SharePoint站点中创建一个自定义JS文件(比如
方案3:用postMessage实现跨域通信(不同源场景)
如果外部页面和SharePoint站点不同源(比如域名不同但同属内网),可以用HTML5的postMessage API安全传递调用请求:
- 步骤:
- 在包含
openDialogSearch的SharePoint页面中添加消息监听:window.addEventListener('message', function(event) { // 严格验证消息来源,只处理可信的外部页面 if (event.origin === 'http://你的外部页面域名') { if (event.data.type === 'triggerSearch') { // 调用目标函数 openDialogSearch(event.data.resourceUrl); } } }, false); - 在外部HTML页面中通过iframe发送消息:
<iframe id="spFrame" src="http://你的SharePoint站点地址/包含函数的页面路径" style="display: none;"></iframe> <script> document.getElementById('spFrame').addEventListener('load', function() { this.contentWindow.postMessage({ type: 'triggerSearch', resourceUrl: 'http://目标资源的URL' }, 'http://你的SharePoint站点域名'); }); </script>
- 在包含
内容的提问来源于stack exchange,提问作者skatz
相关产品推荐
相关产品推荐

