【问题标题】:How to change url in a div element, which is loaded by iframe with javascript如何更改由 iframe 和 javascript 加载的 div 元素中的 url
【发布时间】:2018-04-11 12:03:19
【问题描述】:

在我的 manifest.json 中:

"content_scripts": [
        {
        "matches": [
            "http://*/*",
            "https://*/*"
            ],
        "css":["style.css"],
        "js": ["./js/jquery-3.3.1.js","content-script.js", "./search-api/search-api.js"],
        "run_at": "document_end"
        }
    ],

在 content-script.js 中

var height = "40px";
var iframe = document.createElement("iframe");
iframe.src = chrome.extension.getURL("toolbar.html");
iframe.style.height = height;
iframe.style.width = "100%";
iframe.style.position = "fixed";
iframe.style.top = "0";
iframe.style.left = "0";
iframe.style.zIndex = "938089"; // Some high value
// Etc. Add your own styles if you want to
document.documentElement.appendChild(iframe);

// continuing add-toolbar.js
var bodyStyle = document.body.style;
var cssTransform = 'transform' in bodyStyle ? 'transform' : 'webkitTransform';
bodyStyle[cssTransform] = 'translateY(' + height + ')';

工具栏.html:

<div style="color:aqua">
    <a target="_blank" href="https://www.uber.com" id="toolbars">Uber cool home page</a>
</div>

这会将 iframe 加载到我的网页中。但我想动态更改链接的 url。假设我想将其从 uber.com 更改为 amazon.com。

试过了:

iframe.find('toolbars').href("www.amazon.com")

【问题讨论】:

  • 是否使用 jquery?
  • 试试这个:$('#toolbars', parent.document).attr ('href', 'www.amazon.com');
  • jquery,当然 :)
  • @wayneOS parent.document 是做什么的?我想知道它指的是什么。
  • @kai 对不起,我弄错了。你需要的是$('iframe').contents ().find ('#toolbars').attr ('href', 'www.amazon.com');。需要 parent.document 将父窗口中的内容从 iframe 上下文中更改出来。

标签: javascript jquery iframe google-chrome-extension


【解决方案1】:

最简单的方法是使用 JavaScript 或 jquery。

  1. JavaScript:

    document.getElementById("toolbars").setAttribute("href", "www.amazon.com");

  2. jQuery:

    $('#toolbars').attr('href', 'www.amazoncom');

【讨论】:

    【解决方案2】:

    要访问嵌入 iframe 中的元素,您首先需要访问它contents(),然后使用find() 获取它的元素。在你的情况下,看起来像:

    $('iframe').contents ().find ('#toolbars').attr ('href', 'www.amazon.com');
    

    【讨论】:

      【解决方案3】:

      你可以这样做。

      $(‘#iframID’).attr(‘src’,’your url’);
      

      有一个完美的答案here

      【讨论】:

        猜你喜欢
        • 2011-09-20
        • 2019-08-13
        • 2017-11-12
        • 1970-01-01
        • 2014-03-29
        • 2021-04-05
        • 2016-07-14
        • 2017-12-02
        • 2011-03-05
        相关资源
        最近更新 更多