2

This might seem a weird question, but is there a way to override the window.location without making the browser control navigate to it? The problem I am having is that i am injecting html code in the control, and the window.location is about:blank - causing errors on some javascript code. Trying to make them think they are in a URL other than about:blank

skaffman
  • 398,947
  • 96
  • 818
  • 769
timeitquery
  • 251
  • 1
  • 5
  • 14

3 Answers3

2

I've had success with Object.defineProperty() when document.documentMode >= 9 (IE9+).

To get the WebBrowser control in IE9+ mode, I first load the following URL:

about:<!doctype html><meta http-equiv="X-UA-Compatible" content="IE=edge">

This gives a mostly empty document in the latest document mode.

Then to redefine window.location, I execute some script via eval() or document.write():

Object.defineProperty(window, 'location', {value: {href: 'fubar'}});

The complete sequence is like this:

  • Load the control.
  • Wait for WebBrowser.ReadyState == 4 or the DocumentComplete event.
  • Call document.open() (important).
  • Eval or write the script redefining location.
  • Write the HTML content.
  • Call document.close() (ensures onload gets called).

Note: I use the ActiveX WebBrowser control, and not the .NET component which is a wrapper around that control. It will probably work the same in .NET.

Lexikos
  • 987
  • 6
  • 16
0

It is not possible to replace the window.location property. window.location is a non-configurable property, which means that it cannot be modified.

The only messy workaround that I can use is to do a find and replace (replace the window.location line with an empty string or something) on the script text before executing it.

XP1
  • 6,910
  • 8
  • 54
  • 61
0

HTML5 drafts include window.history.pushState+window.onpopstate, but this is not supported by Trident (MSHTML), and doesn't allow for navigating across domains, nevermind URL schemes.

Some JavaScript implementations also support user-defined getters and setters, so you could maybe do window.__defineGetter__('location', function() { return fakeLocation }), but yet again I believe that won't work with IE's control.

Echoing the commenters: what are you doing?

ephemient
  • 198,619
  • 38
  • 280
  • 391
  • A little hard to explain on a public forum, but hacking the control pretty much to display certain code i want to display and monitor. the problem is they have JavaScript that checks on the window.location - which breaks. Of course the answer could be dont inject in the browser, navigate to a URL - but i was trying to avoid that. – timeitquery Nov 10 '10 at 15:26
  • Won't work. `Unhandled Error: __defineGetter__: invalid modification of non-configurable property` – XP1 Dec 13 '13 at 06:08