在 Javascript 中调用自定义协议 [英] Make a call to a custom protocol in Javascript
问题描述
我正在 UIWebView 中运行一个脚本,该脚本将数据发送回主机应用程序(在 Objective-C 中).如果我在页面上放一个指向 myprotocol://some_data
的链接,我会收到主机端的信息.
I'm running a script in a UIWebView which sends data back to the host application (in Objective-C). If I put a link on the page pointing to myprotocol://some_data
, I receive the information on the host side.
如何在没有用户交互的情况下在纯 Javascript 中实现相同的行为?类似于 AJAX 调用,但不是通过 HTTP 调用?
How can I achieve the same behaviour in pure Javascript, without user interaction? Something like a AJAX call, but not over HTTP?
我使用的是 AngularJS,但欢迎任何 Javascript 解决方案.
I'm using AngularJS, but any solution in Javascript is welcome.
推荐答案
我发现如果不以某种方式作弊",就无法做到这一点.我决定在我的页面中创建一个 <a>
元素并动态更改其 href
属性,然后使用 Javascript 在其上触发 click
事件.这是我所做的:
I found that there was no way to do this without "cheating" in some way. I decided to create a <a>
element in my page and dynamically change its href
attribute, then triggering the click
event on it with Javascript. Here is what I did :
CSS
a#sendToiOS {
display:block;
position: fixed;
bottom: -1px;
right: -1px;
z-index: -1;
opacity: 0;
width: 1px;
height: 1px;
}
Javascript
var sendToiOS = function(protocol, action, params) {
var e = document.createElement('a');
e.id = 'sendToiOS';
var strParams = "";
if(typeof params !== 'undefined') {
Object.keys(params).forEach(function(key) {
strParams += strParams != "" ? '&' : '';
strParams += key+'='+encodeURI(params[key]);
});
}
e.href = strParams.length > 0 ? protocol+'://'+action+'?'+strParams : protocol+'://'+action;
document.getElementsByTagName('body')[0].appendChild(e);
e.click();
e.parentNode.removeChild(e);
}
调用 sendToiOS('mycustomprotocol', 'some_action', {foo: 'bar', foo2: 1337});
然后会触发对 mycustomprotocol://some_action?foo 的调用=bar&foo2=1337
.
Calling sendToiOS('mycustomprotocol', 'some_action', {foo: 'bar', foo2: 1337});
would then trigger a call to mycustomprotocol://some_action?foo=bar&foo2=1337
.
这篇关于在 Javascript 中调用自定义协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!