Injecting CSS rules into the page in Android Brows

2019-08-28 12:12发布

问题:

I'm writing a JavaScript to inject a new CSS rule into pages in Android browser in order to display some text in a custom CSS font (after some replacement).

Here is how I tried to inject the CSS rule:

var css = '@font-face {font-family:"font"; src:url(http://www.example.com/font.ttf);} si{font-family:"font"}';
if(document.getElementsByTagName("style")[0]){
   var style = document.getElementsByTagName("style")[0];
} else {
   var style = document.createElement("style");
   style.type = "text/css";
   document.getElementsByTagName("HEAD")[0].appendChild(style);
}
var sheet = style.sheet;
sheet.insertRule(css, sheet.cssRules.length);

Then the text is replaced using a JavaScript XPath implementation. Replacing lines are in this model:

text = text.replace(/\'/g, "<si>♥</si>");

The text replacement happens perfectly. But the injecting CSS rule part is not working. The replaced text is just shown as <si>♥</si> (with tags also printed). :(

Can anyone please correct my code of injecting CSS rule or please suggest some other way to do this.

Thanks!

Update: I'm emulating this in Android 2.2 which supports CSS fonts.

回答1:

@font-face seems to be broken on Android 2.0 and 2.1 (bug tracker).