在Internet Explorer中使用JavaScript覆盖外部对象的功能 [英] Overriding external object's function using JavaScript in Internet Explorer

查看:110
本文介绍了在Internet Explorer中使用JavaScript覆盖外部对象的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个仅使用IE的项目,该项目使用主机应用程序提供的外部对象模型。 Internet Explorer允许通过浏览器组件访问此外部对象:
http://msdn.microsoft.com/en-us/library/ie/ms535246(v = vs.85).aspx

I am currently working on an IE-only project which makes use of an external object model provided by the host application. Internet Explorer allows access to this external object through browser components: http://msdn.microsoft.com/en-us/library/ie/ms535246(v=vs.85).aspx

对象的访问采用JavaScript函数调用的形式,类似于:

Access to the object takes the form of JavaScript function invocations, similar to:

external.MethodName(arg1, arg2);

最近对应用程序流程的一个更改将引入数百个(如果不是数千个)if语句条件围绕这些JavaScript调用,例如:

One of the recent changes to the application flow will introduce hundreds, if not thousands of if-statement conditionals around these JavaScript invocations, e.g.:

if (X) {
    external.MethodName(arg1, arg2);
} else {
    // do something else
}

如果我们可以覆盖或重写外部对象的函数,那么if条件只出现在一个地方,而不是修改可能成千上万的HTML文件。通常,这可以在JavaScript中完成:

Rather than modify potentially thousands of HTML files, it would seem to make sense if we could override or rewrite the external object's functions so that the if condition only appears in one place. Normally, this could be accomplished in JavaScript with:

external.OldMethodName = external.MethodName;
external.MethodName = function(arg1, arg2) {
    if (X) {
        external.OldMethodName(arg1, arg2);
    } else {
        // do something else
    }
};

但是,这会导致无效的过程调用或参数脚本错误,因为您无法引用这种方式使用外部主机方法。

However, this results in an "Invalid procedure call or argument" script error, because you cannot reference the external host method this way.

我无法访问主机应用程序专有代码来直接更改外部方法。

I do not have access to the host application proprietary code to change the external method directly.

我有什么方法可以使用JavaScript来覆盖外部对象的函数,或者我需要用if语句包装(潜在的)成千上万的调用(非常糟糕的做法)?

Is there any way I can use JavaScript to override the external object's functions, or will I need to wrap the (potential) thousands of invocations with if-statements (a very bad practice)?

更新经过与客户的多次反复,我们设法与第三方联系供应商更新外部主机方法,这比我们在前端包装方法的方法要好得多。在此期间我接受了保罗的回答。

UPDATE: After much back-and-forth with the client, we have managed to reach out to the third-party vendor to update the external host method, which is vastly preferable to our method of wrapping the method on the front end. I have accepted Paul's answer in the meantime.

推荐答案

使用toString()和eval:

Use toString() and eval:

var foo = external.MethodName.toString().replace("OldMethodName", "MethodName").replace("bar","baz");
eval(foo);
if(x) 
  { 
  external.OldMethodName(arg1,arg2);
  }
else
  {
  MethodName(arg1,arg2)
  }

这篇关于在Internet Explorer中使用JavaScript覆盖外部对象的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆