注入了第三方javascript,它会在构建特定路径的某些逻辑之后创建一个新的Image(),但不会将其附加到文档中。
(function(){
{....}
new Image().src = "some_image_path";
})();
问题是我希望能够得到生成的“some_image_path”。我不知道要改变它什么,只是得到价值。我无法控制第三方JS并且无法更改。我尝试过使用cujojs / meld但它没有做任何事情或者出现“非法调用”错误。
有没有办法通过观察Image / HTMLImageElement对象或自动将onload属性添加到我定义的函数的所有Image实例来获得src值是什么?
答案 0 :(得分:1)
您可以尝试使用自定义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>