如何在div元素中更改url,这是由iframe用javascript加载的

时间:2018-04-11 12:03:19

标签: javascript jquery iframe google-chrome-extension

在我的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 + ')';

toolbar.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")

3 个答案:

答案 0 :(得分:0)

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

  1. JavaScript的:

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

  2. JQuery的:

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:-1)

你可以这样做。

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

有一个完美的答案here