2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptとか文字化け

2
Posted at

以下の処理では文字化けするものがあります。何行目かお分かり頂けるでしょうか。

new Worker(URL.createObjectURL(new Blob(["console.log(1,'一丁')"])));
new Worker("data:,console.log(2,'一丁')");
new Worker("data:,console.log(3,'\u4e00\u4e01')");
new Worker("data:,console.log(4,'\\u4e00\\u4e01')");
new Worker("data:,console.log(5,'%E4%B8%80%E4%B8%81')");
new Worker("data:,"+encodeURIComponent("console.log(6,'一丁')"))
new Worker("data:;charset=utf-8,console.log(7,'一丁')");
new Worker("data:application/javascript,console.log(8,'一丁')");

2、3、5、6回目のnew Workerにおいて文字化けが発生します。多分。
1回目の場合、まずBlob objectを作成する際、browserは文字列「一丁」を既定で UTF-8 形式のbinay dataとして保存します。それを URL.createObjectURL でmemory上の URLに紐付けているため、Worker は文字符号を正しく解釈でき、文字化けしません。
しかし、data URLに直接日本語のような非ASCII文字を含めると、browserや環境によって文字符号の解釈に不整合が起きます。
特に data:,... のように文字符号(charset=utf-8等)を明示していない場合、browserは意図しないbyte列として読み込んでしまうため、「一丁」という文字が壊れて文字化けしてしまいます。
ではなぜ3、5、6回目が文字化けするのかって? 8回目がなぜ文字化けしないかって? それをここに書くには余白が狭過ぎるって奴だぜ。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?