开发者

Javascript injection problem in Android 2.1 emulator but fine in 2.2

开发者 https://www.devze.com 2023-03-05 00:47 出处:网络
I\'m trying to dynamically inject some CSS into a webpage loaded into an Android WebView. I\'ve distilled the problem down to this HTML which if you insert into the body of a plain HTML page adds red

I'm trying to dynamically inject some CSS into a webpage loaded into an Android WebView.

I've distilled the problem down to this HTML which if you insert into the body of a plain HTML page adds red boxes to the elements on the page on Android 2.2 when you tap "Click me" but fails on 2.1 (when run in the emulator anyway).

<a href="javascript:(function() { var style=document.createElement('style');style.type='text/css';style.innerHTML='* { border: 1px solid red; }';document.getElementsByTagName('head').item(0).appendChild(style);})();">Click me.</a&开发者_JAVA技巧gt;

Any idea if there is a way I can get this JS to work on Android 2.1? Or if it is an emulator only bug?

Thanks


I've finally found a solution and so can answer my own question!

It seems Android 2.1 doesn't like innerHTML for script tags. The more correct way to do this is to use document.createTextNode() and works in both 2.1 and 2.2.

<a href="javascript:(function() { var style=document.createElement('style');style.type='text/css';css = document.createTextNode('* { border: 1px solid red; }');style.appendChild(css);document.getElementsByTagName('head').item(0).appendChild(style);})();">Click me to change all styles</a>
0

精彩评论

暂无评论...
验证码 换一张
取 消