首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Chrome扩展中,你能在一切之前强制注入一些javascript吗?

在Chrome扩展中,你能在一切之前强制注入一些javascript吗?
EN

Stack Overflow用户
提问于 2018-06-21 04:55:39
回答 1查看 358关注 0票数 6

我有一个Chrome扩展(下面提供的源代码),它被发现存在竞争条件。我需要一些注入的JavaScript运行在所有其他网页上的JavaScript之前。

下面是我要做的一个简单示例的源代码:https://github.com/nddipiazza/oogi

它试图将名称空间添加到所有将作为cookie保存的cookie名称,但同时从正在使用的cookie中删除这些名称空间。

因此,假设通常没有扩展,你会有两个cookie,它们是在访问一个站点后保存的:

JSESSIONID
lastVisit

此扩展会将它们保存为:

oogi$JSESSIONID
oogi$lastVisit

这个扩展基本上有两个主要部分。

这里的问题是,为了让它工作,我需要inject.js中的javascript cookie头截获绝对总是在任何其他javascript之前加载。但事实并非如此。

示例:内联javascript中的Cookie,例如:

<body>
<H2>Cookies from Inline JavaScript</H2>
<script>
    console.log("Inline javascript is executed.");
    document.write(listCookies());
</script>
</body>

在加载注入cookie拦截器之前就已经加载了。您可以从控制台中看出日志将按以下顺序读取:

Inline javascript is executed.
cookie get/set injector completed

有没有办法修复这种注入争用情况?我想让chrome扩展在页面上执行任何javascript之前强制运行javascript。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-23 14:19:45

多亏了这张票据上的注释,在我的案例中,解决方案是来自以下答案的方法2:https://stackoverflow.com/a/9517879

特别感谢https://stackoverflow.com/users/3959875/woxxom

以下是指向最终解决方案的链接:

https://github.com/nddipiazza/oogi/commit/64e1ef8dc3abfb32fec2db5fb67891a29cfe12ea

产生差异的代码的重要部分在下面

var actualCode = `var cookieGetter = document.__lookupGetter__("cookie").bind(document);
var cookieSetter = document.__lookupSetter__("cookie").bind(document);
var getPrefix = function() {
    return "oogi$"
};
var processCookieStr = function(cookiesStr) {
    var prefix = getPrefix();
    var cookieStrList = cookiesStr.split('; ');
    var newStrList = [];
    cookieStrList.forEach(function(cookieStr){
        if (cookieStr.indexOf(prefix)==0) {
            newStrList.push(cookieStr.substring(prefix.length, cookieStr.length));
        }
    });
    return newStrList.join("; ");
};
var processSetCookieStr = function(str) {
    console.log("Processing set cookie string " + str);
    return getPrefix()+str;
};
Object.defineProperty(document, 'cookie', {
    get: function() {
        var storedCookieStr = cookieGetter();
        console.log("Intercepted a cookie get " + storedCookieStr + " , and returning processed cookie string " + processCookieStr(storedCookieStr));
        return processCookieStr(storedCookieStr);
    },
    set: function(cookieString) {
        var newValue = processSetCookieStr(cookieString);
        console.log("Intercepted a cookie set " + newValue)
        return cookieSetter(newValue);
    }
});
console.log("cookie get/set injector completed");
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50956891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档