Google chrome extensions: dispatchevent in main web page

懵懂的女人 提交于 2020-01-11 11:22:28

问题


I have in my extension content script. From content script I tried dispatch event at main web page. But event didn't dispatch, nothing. For greater certainty I dispatch events in all elements =)

$('*').each(function(i, entity){
    console.log(entity);
    $(entity).trigger('mouseenter');
});

From this article, I found that extension has limited scope and no access to main page script variables.

But can I trigger elements event at main page from extension content script?

Sorry for my bad english!


回答1:


If the event listener was defined in the context of the web page (but not on the content script), then the triggered 'mouseenter' from the content will not be handled. It happens because content scripts live in an isolated world.

To achieve the correct triggering, you need to insert the JavaScript directly into the web page context. You have the following options:

Option 1: simple with inline JavaScript

Insert the code into a <script></script> tag and append it to the document:

var script = "$('*').each(function(i, entity){\
  console.log(entity);\
  $(entity).trigger('mouseenter');\
});";

var scriptElement = document.createElement("script");
scriptElement.innerHTML = script;

document.head.appendChild(scriptElement);

Option 2: Web accessible JavaScript file

This approach is useful when the injected script has a lot of code.

Create a file in the extension root directory, for example inject.js with the following content:

$('*').each(function(i, entity){
    console.log(entity);
    $(entity).trigger('mouseenter');
});

Modify the manifest.json to make it web accessible:

{
  "web_accessible_resources": ["inject.js"]
}

And in the content script create a <script/> tag, referencing the inject.js:

var scriptElement = document.createElement("script");
scriptElement.setAttribute('src', chrome.runtime.getURL('inject.js'));
document.head.appendChild(scriptElement);


来源:https://stackoverflow.com/questions/34975823/google-chrome-extensions-dispatchevent-in-main-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!