JavaScript - 如何注入不同的函数实现,例如 alert(与 web 和 Node 共享模块.js服务器端)
JavaScript - how to inject different implementation of function e.g. alert (sharing modules with web & Node.js server side)
情况:有大量的JavaScript文件。我想在 Node.js 上运行它们。
但是有几个地方,例如 使用alert()
,会导致 Node.js 失败。
当然,有办法查看每个文件并添加导入,例如
alert = require('console').log
但这会阻止这些文件在INN浏览器(在客户端)工作。
有没有办法注入不同的alert
实现?那是在不修改源的情况下更改/添加函数实现?
在代码的开头,写:
global.alert = console.log;
基本版本
在文件silentalert.js
内
if(typeof global != "undefined"){
global.alert = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
}
在 NodeJS 脚本中:
require('./silentalert');
此代码将在 NodeJS 中打印警报消息以console.log
,但在浏览器中运行时仍将使用 alert
。
下一个实现提供了一种更通用的方法。
跨平台版本
在文件silentalert.js
内
var g = typeof global != "undefined" ? global : (typeof window != "undefined") ? window : {};
var c = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
var _old = g.alert;
var silentalert = function(activate){
g.alert = activate ? c : _old;
};
if(typeof module !== "undefined"){module.exports = silentalert;}
在 NodeJS 脚本中:
var silentalert = require('./silentalert');
silentalert(true);
// or silentalert(typeof window == "undefined") if you just want to silent alert() on NodeJS
// your script...
silentalert(false);
您甚至可以直接在HTML页面中包含silentalert.js:
<script src="./silentalert.js" type="text/javascript"></script>
<script type="text/javascript">
silentalert(true);
// your script...
silentalert(false);
</script>
注意:如果您需要支持 IE8 .bind
在这种情况下不可用,请替换:
var c = typeof console != "undefined" && console.log ? console.log.bind(this) : function(){};
跟
var c = typeof console != "undefined" && console.log ? function(){console.log.apply(console, arguments);} : function(){};
这两个脚本都允许您在 NodeJS 中静默警报,同时仍然能够在客户端使用它们。
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- RegEx删除空属性?例如,如果(class=“”||class=“”)移除;否则就下课
- 在Web应用程序中使用Highcharts javascript
- WebDriverException:tinyMCE未在selenium Web driver java中定义
- Selenium Web驱动程序和javascript
- Windows形成web浏览器控件和Javascript更改的DOM
- 如何将javascript事件从web浏览器wpf控件发送到wpf的c#代码
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- 在调用speak之前预加载Web Speech API
- 如何在visualstudio中调试web api时编辑javascript文件
- 是否存在React Native“;WEB代码安全防护”;
- 如何在Ionic Android中将Javascript注入到web视图中
- 将复杂对象从angular js传递到web api,它总是返回404
- JavaScript:不允许Web Worker使用(例如)XmlHttpRequest
- 基本的 dojo 1.7 简单的 Web 应用程序,具有优雅的基础架构(例如 Dojo 样板)
- 有没有办法将Google Analytics for Web置于“试运行”模式,例如GA移动SDK
- 如何仅使用Web技术(例如HTML,CSS和Javascript)重新创建图像,例如.png或.jpg
- JavaScript - 如何注入不同的函数实现,例如 alert(与 web 和 Node 共享模块.js服务器端)
- 创建模态窗口,例如 Google Keep for Web
- 如果web浏览器用户修改Javascript并执行它(例如从控制台),它是否违反同源策略?