Chrome脚本访问window对象

var isChrome = window.chrome;

 

function safeInvoke(callback) {

///

沙箱模式下的回调

 

//因为Chrome不支持require引入脚本包的功能,为避免需要将整个jQuery加载进来,这里使用非安全模式进行执行

if (isChrome) unsafeInvoke(callback);

else callback();

}

 

 

function unsafeInvoke(callback) {

///

非沙箱模式下的回调

var cb = document.createElement("script");

cb.type = "text/javascript";

cb.textContent = buildCallback(callback);

document.head.appendChild(cb);

}

 

function buildCallback(callback) {

var content = "";

content += "window.__cb=" + buildObjectJavascriptCode(callback) + ";\r\n\

window.__cb();\r\n\

";

return content;

}

 

function buildObjectJavascriptCode(object) {

///

将指定的Javascript对象编译为脚本

if (!object) return null;

 

var t = typeof (object);

if (t == "string") {

return "\"" + object.replace(/(\r|\n|\\)/gi, function (a, b) {

switch (b) {

case "\r":

return "\\r";

case "\n":

return "\\n";

case "\\":

return "\\\\";

}

}) + "\"";

}

if (t != "object") return object + "";

 

var code = [];

for (var i in object) {

var obj = object[i];

var objType = typeof (obj);

 

if ((objType == "object" || objType == "string") && obj) {

code.push(i + ":" + buildObjectJavascriptCode(obj));

} else {

code.push(i + ":" + obj);

}

}

 

return "{" + code.join(",") + "}";

}

你可能感兴趣的:(Chrome脚本访问window对象)