I have developed a JS library that renders layouts (similar to layout rendering as in Razor View Engine in ASP.Net MVC). In order to display the final result, I replace the whole document by calling the document.write(...) function. For example:
document.open()
document.write(renderedLayout)
document.close()
I'm using this methods because I need all scripts whether defined by the developer or acquired from an external resource to be run and evaluated right after the content is replaced. That said, replacing the inner HTML of the html node will fail.
The methods I described works in Opera, Chrome, and Firefox but when I try to test it under IE and Edge, it fails and the browser does not showing anything once the write method is called.
My test shows that, all console outputs are received just before write is called and after that everything disappears.
Even though some may suggest that it could be a security measure in IE or Edge which might be solved by changing their configs, I would like to know how I can solve it using pure JavaScript so that my solution could be used in all major browsers.
I have traced and tested my code carefully, and I'm 100% sure the block of code I attached in the question is causing the blocking.
document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
removing document.open() and document.close() might help.
Next time when you are confused if your function written works on browser,
Open console(use ctrl+i or F12) - In Console place your Javascript code.
Here is the reference for you : https://developer.mozilla.org/en-US/docs/Web/API/Document/write
Related
I'm experimenting with a simple Javascript debugger for a WebView. I'd like to debug/control/inspect how some Javascript code is being executed inside my WebView.
I haven't found any solution other than using the WebChromeClient to receive the console messages.
Since I have access to the Javascript code I can add instrumentation code: a console.log call before each line, with a special message (e.g. "debugging line 3") that tells which lines have been executed.
It's quite rudimentary so I wonder if there's any better solution. It would be great if I could use the debugger statement to really control execution flow.
This is what I have been doing if I want to console.log() anything directly on the mobile browser so that debugging can be done on the actual device and not in emulator or similar...
I made JS debugger plugin and here is what it have:
it creates an absolutely positioned HTML element that is placed on top of the content and is semi transparent.
I made the JS logic that actually simulates what console.log() does and print out all desired information in mentioned HTML element
once plugin was done I simply used MoibileDebugger.log('what ever'); instead of console.log('what ever');
My code is still not published publicly but will do that soon, so that anyone can benefit from using it...
In any case this plugin can be made very quickly by anyone who is good in JS.
I'm having a JavaScript debugging question. I would like to know, how it would be possible to find out in which file/line a new script is loaded and called. My website has several scripts which are appended via document.write(), and I would like to find a way to find the function call in all attached scripts of the website.
I would prefer either Firebug or Chrome Dev tools.
Thanks!
Neither Firebug nor the Firefox or the Chrome DevTools currently allow to debug code inserted via document.write(). I created bug 1122222 for the Firefox DevTools and issue 449269 for the Chrome DevTools requesting to be able to debug such scripts. As upcoming Firebug versions will be based on the Firefox DevTools, it will offer this feature once the Firefox bug is fixed, so there's no need to create a separate issue for it.
Until the above bugs are fixed you need to use another method to inject your script in order to be able to debug it within the browser.
Method 1: using eval()
You can use the eval() function to evaluate arbitrary code dynamically. Note that the eval() only evaluates JavaScript code, it must not be surrounded by any HTML.
Example:
eval("console.log('Hi!')");
Method 2: injecting a <script> tag
You can add a <script> tag to the page and then add contents to it.
Example:
var script = document.createElement("script");
script.textContent = "console.log('Hi!');";
document.body.appendChild(script);
Method 3: using new Function()
You can create a new function via the Function constructor.
Example:
(new Function("console.log('Hi!');"))();
Note that JavaScript won't be executed using innerHTML or insertAdjacentHTML() due to security reasons.
I ran into this problem today in IE6 (but is reproducible on all recent version of IE).
I noticed quite a few people run into this problem and I haven't seen a very practical way to fix this.
There seems to be some other solution floating about regarding the order of script tags and meta tags in the head of the HTML document. I haven't confirm this but here's a link anyway:
What causes the error "Can't execute code from a freed script"
I also know the solution to this problem so I'm posting it below
First of all you need to locate the source of the message.
IE is known for it's abysmal error reporting but luckily IE9 seems somewhat capable. If this bug occurs in IE6, IE7 or IE8 it will also occur in IE9, so use IE9 to debug (for your sanity)
Open the webdeveloper console in IE9 (press F12) and run through the steps to produce this error.
IE9 should now give you a file and line indication on the console, yay!
What typically goes wrong is a callback that is executed after some delay, either by setTimeout or because of an Ajax request. If the window, document or frame the callback is defined in got unloaded then you will get this message when it tries to execute your callback function.
Seemingly other browsers ignore this problem, which is fine I guess. To make IE do the same just wrap the callback in a try-catch block (I don't know what the callback would evaluate to, I don't think it evaluates to undefined). If you want have more precise error handling or if you actually want to take action when this occurs you can probably do so and please make a post here because I'm curious as to what kind of use case would actually require this.
If you have page that uses several Frames, this error might be caused by objects initialized in one frame being used in some other frame after the initial frame was removed from the page.
When that happens, then depending on situation, you might want to:
Review your code looking for potential memory leaks
If those object represent some data you do actually want passed between frames, then consider using their stringified form instead.
The solution - be sure to place all META statements BEFORE any script statements.
On the server lies a html file with javascript code included.
This javascript code includes a method called something like "CheckObject".
This file works for all users, except one specific (but important).
He gets a javascript error and in his browser sourcode appears something unbelievable:
The methodname "CheckObject" is replaced with "Check!==ect", means the "Obj" of the method name is replaced with !==.
Why could that be?
Hope anybody can help me!
Best regards
If he's using a browser that supports extensions (like Firefox, Chrome, and some others), it's probably worth disabling all of the extensions and seeing if the problem goes away.
If you haven't already, I'd completely clear his cache in case there was a bad page transfer once and the browser is reusing it.
I can't imagine how it would be happening reliably otherwise.
I have an ASP.NET MVC project that uses some simple AJAX functionality through jQuery's $.get method like so:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
});
The amount of content is relatively low here -- usually a single div with a short blurb of text. Sometimes, however, I am also injecting some javascript into the page. At some point when I dynamically include script into content that was itself dynamically added to the page, the script still runs, but it ceases to be available to the debugger. In VS2008, any breakpoints are ignored, and when I use the "debugger" statement, I get a messagebox saying that "no source code is available at this location." This fails both for the VS2008 debugger and the Firebug debugger in Firefox. I have tried both including the script inline in my dynamic content and also referencing a separate js file from this dynamic content -- both ways seemed to result in script that's unavailable to the debugger.
So, my question is twofold:
Is there any way to help the debugger recognize the existence of this script?
If not, what's the best way to include scripts that are used infrequently and in dynamically generated content in a way that is accessible to the debuggers?
I can not comment yet, but I can maybe help answer. As qwerty said, firefox console can be the way to go. I'd recommend going full bar and getting firebug. It hasn't ever missed code in my 3 years using it.
You could also change the way the injected javascript is added and see if that effects the debugger you're using. (I take it you're using Microsoft's IDE?).
In any case, I find the best way to inject javascript for IE is to put it as an appendChild in the head. In the case that isn't viable, the eval function (I hate using it as much as you do) can be used. Here is my AJAX IE fixer code I use. I use it for safari too since it has similar behavior. If you need that too just change the browser condition check (document.all for IE, Safari is navigator.userAgent.toLowerCase() == 'safari';).
function execajaxscripts(obj){
if(document.all){
var scripts = obj.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
eval(scripts[i].innerHTML);
}
}
}
I've never used jquery, I preferred prototype then dojo but... I take it that it would look something like this:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
execajaxscripts(result);
});
The one problem is, eval debug errors may not be caught since it creates another instance of the interpreter. But it is worth trying.. and otherwise. Use a different debugger :D
This might be a long shot, but I don't have access to IE right now to test.
Try naming the anonymous function, e.g.:
$.get(myUrl, null, function anon_temp1(result) {
$('#myselector').html(result);
});
I'm surprised firebug is not catching the 'debugger' statement. I've never had any problems no matter how complicated the JS including method was
If this is javascript embedded within dynmically generated HTML, I can see where that might be a problem since the debugger would not see it in the initial load. I am surprised that you could put it into a seperate .js file and the debugger still failed to see the function.
It seems you could define a function in a seperate static file, nominally "get_and_show" (or whatever, possibly nested in a namespace of sorts) with a parameter of myUrl, and then call the function from the HTML. Why won't that trip the breakpoint (did you try something like this -- the question is unclear as to whether the reference to the .js in the dynamic HTML was just a func call, or the actual script/load reference as well)? Be sure to first load the external script file from a "hard coded" reference in the HTML file? (view source on roboprogs.com/index.html -- loads .js files, then runs a text insertion func)
We use firebug for debug javascript, profile requests, throw logs, etc.
You can download from http://getfirebug.com/
If firebug don't show your javascript source, post some url to test your example case.
I hope I've been of any help!
If you add // # sourceURL=foo.js to the end of the script that you're injecting then it should show up in the list of scripts in firebug and webkit inspector.
jQuery could be patched to do this automatically, but the ticket was rejected.
Here's a related question: Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or IE8 Developer Tool?