简体   繁体   中英

Object.defineProperty not changing property of element

I am trying to override the src property of all iframes in my application so their src property always gets set to "redirect.html" regardless of what value the HTML tag defines for it. So far, I have come up with the following, but it doesn't seem to be applying to the DOM element:

<!doctype html>
<html>
<head>
    <script>
        var propertyDescriptorSrc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, "src");
        Object.defineProperty(HTMLIFrameElement.prototype, "src", {
            get: function get_src() {
                var val = propertyDescriptorSrc.get.call(this);
                return "redirect.html";
            },
            set: function (val) {
                alert('setting: ' + val);
                propertyDescriptorSrc.set.call(this, val);
            }
        });
    </script>
</head>
<body>
    <iframe src="page.html"></iframe>
</body>
</html>

I expected the iframe element in the body to load redirect.html instead of page.html, since I overrided its "getter", but it still loaded page.html. Is there a way to force this behavior where all iframes by default go to redirect.html instead of whatever is defined in their src attribute?

(This is just an experimental project)

Before it starts javascript, the DOM tree is already parsed and contains all iframes together with its src, according to the Critical Rendering Path. The only way to do this is by using javascript to redefine the src attributes of the individual iframe node. For example, as below.

all iframes are set to redirect.html:

<!doctype html>
<html>
<head>

</head>
<body>
    <iframe src="page.html"></iframe>
    <iframe src="page2.html"></iframe>
<script>
( function(){
    var lng = document.getElementsByTagName('iframe').length;
    for (var i=0; i<lng;i++){
    document.getElementsByTagName('iframe')[i].src="redirect.html";
    }
})();
</script>
</body>
</html>

According to the suggestion, @Aaron Digulla gives a more readable form of function. It seems that the search algorithms of the DOM tree are so efficient today that the argument is the readability of the record, not the efficiency.

    (function(){
    var frames = document.getElementsByTagName('iframe');
    for (var i=0; i<frames.length;i++){
        frames[i].src="redirect.html";
    }
    })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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