Javascript 添加监听器或自动将属性添加到所有新的 Image() 实例

标签 javascript

有一个第 3 方 javascript 被注入(inject),它在一些逻辑之后创建一个新的 Image() 来构建一个特定的路径,但不会将它附加到文档中。

(function(){
    {....}
    new Image().src = "some_image_path";
})();

问题是我希望能够得到生成的结果“some_image_path”。我不想改变它或任何东西,只是获得值(value)。我无法控制第 3 方 JS,也无法更改。我试过使用 cujojs/meld,但它要么什么也没做,要么出现“非法调用”错误。

有没有办法通过观察 Image/HTMLImageElement obj 或通过自动将 onload 属性添加到我定义的函数的所有 Image 实例来获取 src 值?

最佳答案

您可以尝试使用自定义的 Image 构造函数在闭包中加载第三方脚本。

(function() {
  var img;
  var Image = function Image() {
    return img = new (Function.prototype.bind.apply(window.Image, arguments));
  }

  // This is where the 3rd party code should be injected.
  // I'm assuming that since you're including it on your page, you know its source and trust it enough to `eval` it.
  // You won't be able to use a `<script>` tag to load it since that would execute in the global scope.
  // You'll likely need to use AJAX to fetch the script contents and pass to eval here.
  eval("new Image().src = some_image_path");

  return img;
})().src == some_image_path;

编辑:

您可以改为覆盖全局 Image(然后再修复它)。由于脚本标签是按顺序计算的,所以这应该有效。

<script>
  var img;
  var oldImage = Image;
  Image = function Image() {
    return img = new (Function.prototype.bind.apply(oldImage, arguments));
  }
</script>

<script src="..."></script>

<script>
  // img now contains the instantiated `Image` object
  img.src; // do what you will with this

  // Clean up
  Image = oldImage;
</script>

关于Javascript 添加监听器或自动将属性添加到所有新的 Image() 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092189/

相关文章:

javascript - 如何将异步状态传递给子组件 Prop ?

javascript - Fs 没有正确保存文件以及如何简化此代码

c# - 如何检测 ActiveX 支持?

javascript - 如何在 Node.js 中设置和访问类属性?

JavaScript REGEX - 任意顺序相同的数字 3 次

javascript - 在 React Native 中使用 Fetch API 时处理无法访问的服务器

javascript - 根据值切换案例语句更改文本颜色的颜色

JavaScript 变量更新

javascript - 使用 javascript 删除不需要的空格

javascript - 如何将数据从弹出窗口中继到 vue.js 应用程序