简体   繁体   English

如何更改div元素中的网址,该元素由iframe使用javascript加载

[英]How to change url in a div element, which is loaded by iframe with javascript

In my manifest.json: 在我的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"
        }
    ],

In content-script.js 在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: 工具栏.html:

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

This loads up the iframe into my webpage fine. 这样可以将iframe加载到我的网页中。 But I want to dynamically change the url of the link. 但我想动态更改链接的网址。 Let's say I want to change it to amazon.com from uber.com. 假设我想将其从uber.com更改为amazon.com。

Tried: 尝试过:

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

The Simplest way to do this is to use JavaScript or jquery. 最简单的方法是使用JavaScript或jquery。

  1. JavaScript: JavaScript:

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

  2. JQuery: jQuery的:

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

To access an element in an imbedded iframe you first need to access it contents() and then use find() to get it elements. 要访问嵌入式iframe中的元素,您首先需要访问它的contents() ,然后使用find()获取它的元素。 In your case that would look like: 您的情况如下所示:

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

You can do like this. 你可以这样

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

There is a perfect answer here . 有一个完美的答案在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM