I can get your first case to work if I create an empty html file and issue:
f = webdriver.Firefox()
f.get("file://path/to/empty.html")
After this, the JavaScript you've shown will execute without issue. When I try the code you've shown in the question, Firefox does not give me an error but Chrome says: "Not allowed to load local resource". I believe the problem is cross-domain requests.
The issue with your second case is that behind the scenes Selenium wraps your JavaScript code in an anonymous function. So your blah
function is local to this anonymous function. If you want to make it global, you have to assign it to window
, like this:
>>> from selenium import webdriver
>>> f = webdriver.Firefox()
>>> f.execute_script("window.blah = function () {document.body.innerHTML='testing';}")
>>> f.execute_script("blah()")