防止iframe在不触摸iframe代码的情况下重定向父级

时间:2019-03-09 00:58:08

标签: javascript iframe

我的演示:https://enfrte.neocities.org/code-examples/iframe.html

您好,我有一个本地页面,其中包含一个iframe,如果单击某个事件(“停止加载”按钮),该iframe将具有重定向该本地页面的功能。

在本地页面上,我有一个功能附加到iframe中的重定向按钮上,但是由于该页面在iframe中的重定向功能之后被调用而无法阻止页面重定向。

有什么方法可以通过使用附加到iframe中按钮触发的本地作用域的函数来阻止iframe中执行的功能运行。我无法在我的方案中编辑iframe内容,甚至认为它在同一台服务器上。

谢谢。

本地页面

button_clicked = False
elems = self.find_all_by_xpath(locator="//button[contains(text(),'Got it')]")
for elem in elems:
    if elem.is_displayed():
       elem.click()
       button_clicked = True

if button_clicked == False:
   print("None of " + str(len(elems)) + " buttons are click-able")

iframe的内容

<body>

  <h3>Objective</h3>
  <p>Get NeoCities iframe buttons to also call local function alert.</p>

  <h3>iframe content in pink</h3>
  <iframe id="neocities-iframe" src="https://enfrte.neocities.org/code-examples/button.html"></iframe>

  <p>
  <button id="local_bt" data-bt="Local Button" type="button">Local Button</button>
  </p>

  <script>

  document.querySelector('#neocities-iframe').onload = function() {
    // First get your iframe
    var iframe = document.querySelector('#neocities-iframe');
    // And then the iframe's contentDocument or contentWindow properties 
    var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
    // Check for errors
    if (!iframeDocument) throw "iframe couldn't be found in DOM.";
    // And then get some content in the iframe
    var iframeContentBt1 = iframeDocument.querySelector('#nc_1');
    var iframeContentBtRedirect = iframeDocument.querySelector('#nc_redirect');
    iframeContentBt1.addEventListener('click', local);
    iframeContentBtRedirect.addEventListener('click', local);
  }

  document.querySelector('button').addEventListener('click', local);

  function local(e) {
    alert('Local call: ' + (e.target.value || e.target.innerText));
    e.preventDefault();
  }
  </script>
</body>

0 个答案:

没有答案