如何从父页面调用iframe中的脚本?

msb*_*sbg 4 javascript c# asp.net iframe

我试图从后面的代码中的父页面调用IFrame中的脚本.我用来调用函数的C#:

protected void Page_Load(object sender, EventArgs e)
{
    ...
    string scr = "document.getElementById('mapframe').contentWindow.addPoint(0, 0);"
    ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), scr , true);
}
Run Code Online (Sandbox Code Playgroud)

iFrame的HTML:

 <iframe name="mapframe" id="mapframe" src="Map.html" style="width:100%;height:360px;"></iframe>
Run Code Online (Sandbox Code Playgroud)

和IFrame中的Javascript:

          function addPoint(lat, lon) {
              var myLatlng = new google.maps.LatLng(lat, lon);
              var marker = new google.maps.Marker({
                  position: myLatlng,
                  map: map,
                  title: "Hit"
              });
          }
Run Code Online (Sandbox Code Playgroud)

但是,这会导致此错误:"无法获取未定义或空引用的属性'addPoint'".导致此错误的原因是什么?我已检查以确保contentWindow不为null.

Jua*_*des 5

当您尝试调用该函数时,问题可能是您的iframe未加载

请尝试以下方法

document.getElementById('mapframe').onload = function() {
    // I prefer frames.mapFrame.addPoint();
    document.getElementById('mapframe').contentWindow.addPoint(0,0);
}
Run Code Online (Sandbox Code Playgroud)

甚至

<iframe 
     name="mapframe" 
     id="mapframe" 
     src="Map.html" 
     style="width:100%;height:360px;" 
     onload="this.contentWindow.addPoint(0,0)"></iframe>
Run Code Online (Sandbox Code Playgroud)