简体   繁体   English

JS功能在chrome控制台上有效,但从插件加载时无效

[英]JS function works on chrome console but not when load from plugin

So I have a webpage with a function applaud. 所以我有一个功能鼓掌的网页。 When I call it from the console, I get the normal return: 当我从控制台调用它时,我得到正常的回报:

applaud(3004,1935);
undefined

However, if I use CTG plugins (simple plugin to run a js script), with that code 但是,如果我使用CTG插件(运行js脚本的简单插件),则使用该代码

applaud(3004,1935);

I get the following error in console: 我在控制台中收到以下错误:

3VM5444:1 Uncaught ReferenceError: applaud is not defined
    at <anonymous>:1:1
(anonymous) @ VM5444:1

and function isn't working. 并且功能不起作用。

Do you know how I can use it? 你知道我怎么用吗?

Thanks. 谢谢。

I know this is a bit outdated, but I can answer this. 我知道这有点过时了,但是我可以回答。 (I made the extension in question.) (我进行了扩展)。

Chrome Extensions by default insert scripts into a webpage in a different context than the rest of the page. 默认情况下,Chrome扩展程序在与页面其余部分不同的上下文中将脚本插入网页。 This is for security reasons. 这是出于安全原因。 If you'd like to run code in the context of the webpage, you'd need to use a little workaround. 如果您想在网页的上下文中运行代码,则需要使用一些解决方法。

In the script that the Chrome Extension injects, have that inject a <script> tag into the body of the page. 在Chrome扩展程序注入的脚本中,将<script>标记注入页面主体。 Then that script will be loaded and be able to execute the functions like you can in the console. 然后,该脚本将被加载,并能够像在控制台中一样执行功能。

Here's a demo of code that can do what I'm talking about: 这是一个代码演示,可以完成我正在谈论的内容:

//Create a new script element.
var script = document.createElement("script");

//Get the function you want to inject as a string and add it to the script.
script.innerHTML = injection.toString();

//Add a call to that injection function so it'll automatically execute once it's injected.
script.innerHTML += "injection();";

//Inject that newly created script into the body of the page.
document.body.appendChild(script);

//The contents of this script will be run inside the same context as the webpage.
function injection(){
    applaud(3004, 1935);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM