Javascript 为什么Object.defineProperty在iframe中不工作

Javascript 为什么Object.defineProperty在iframe中不工作,javascript,html,Javascript,Html,我试图定义canvas的属性,但它在iframe中不起作用。如何修复我的代码?谢谢 <html> <head></head> <body> <iframe id="canvas-iframe" sandbox="allow-same-origin"></iframe> <script> const getContext = HTMLCanvasEle

我试图定义canvas的属性,但它在iframe中不起作用。如何修复我的代码?谢谢

<html>
    <head></head>
<body>
        <iframe id="canvas-iframe" sandbox="allow-same-origin"></iframe>
        <script>
            const getContext = HTMLCanvasElement.prototype.getContext;
            Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
                value: function () {
                    let r = getContext.apply(this, arguments);
                    console.log("It's work");
                    return r;
                }
            });

            var canvas = document.getElementById("canvas-iframe").contentDocument.createElement("canvas");    
            var ctx = canvas.getContext("2d")
        </script> 
</body>
</html>

const getContext=HTMLCanvasElement.prototype.getContext;
Object.defineProperty(htmlcanvaseElement.prototype,“getContext”{
值:函数(){
让r=getContext.apply(这是参数);
console.log(“它的工作”);
返回r;
}
});
var canvas=document.getElementById(“canvas iframe”).contentDocument.createElement(“canvas”);
var ctx=canvas.getContext(“2d”)

Object.defineProperty==window.Object.defineProperty
,iFrame有一个不同的
窗口。您必须获得iframe的contentWidow(一旦加载),然后修改它。谢谢。这是工作!也许有一个通用的解决方案?或者我应该找到所有帧并分配每个窗口?好吧,你不能一次修改所有
窗口上的本地人,你必须修改每个。只需在每个帧中插入一个脚本就可以实现您所需的功能,甚至可以从一个dataURL。。。这样,您就不必使用长前缀,您的原始代码也可以工作……您需要修改
iframe.contentWindow.htmlcanvaseElement
的原型,而不是
self.htmlcanvaseElement