簡體   English   中英

無法覆蓋window.location的setter和getter

[英]fail to override setter & getter of window.location

我想更改分配給window.location所有鏈接。 因此,我假設location具有getter和setter。 這就是為什么我克隆它然后覆蓋真正的window.location

  var clonedLocation=Object.assign({},window.location);


            Object.defineProperty( window, 'location', {
              get: function (f) {
                return clonedLocation;
               },
              set:function(o){
                if(typeof o==='string'){
                  o=o+'?id=1';
                }
                clonedLocation=o;
              }
            } );

        };

在編寫時,預期的行為(如果覆蓋完成)為:

window.location='/go';

該腳本應將您重定向到/go?id=1 NOT /go

但是實際的行為是此腳本重定向到/go

==>因此,未覆蓋window.location設置程序,

如何覆蓋window.location的設置器?

可以將 Javascript屬性定義為可configurable: false表示無法重新定義它們。

嘗試重新定義此類屬性將導致類似以下錯誤:

Uncaught TypeError: Cannot redefine property: location

出於安全原因,可以預期主機對象的屬性不可配置。

您可以通過檢查屬性描述符來驗證這一點:

位置的屬性描述符

您習慣用另一個靜態類包裝window.location,該類可以實現鈎子(之前和之后):

看看考普

Aspects.add(
  function op1(){
    console.log("operation one");
    var argument0 = meta.args[0];
    if(typeof argument0==='string'){
        argument0=argument0+'?id=1';
    }
  },
  function op2(){
    console.log("operation two");
  }
)

var DummyLocation = Class({
  set: ["op1", function(newUrl){
    location = newUrl;
  }, "op2"],
  get: [function(){
    return location;
  }]
})

現在您應該使用:

DummyLocation.set("/go");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM