#Variables in website not being set by chrome extension.

223 messages · Page 1 of 1 (latest)

sinful drum
#

I have a basic js script that should set some variables in a website to different values, but for some reason it doesn't accomplish that

console.log('Loaded');

chrome.runtime.onMessage.addListener(gotMessage);

function gotMessage(message, sender, sendResponse) {
  var p = message.txt[0]
  UPunkte = p
  UKokku = p

  var t = message.txt[1]
  tehteidTasemeti = [0, Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5)]
  console.log("Set");
}
runic sequoia
#

nowhere near enough information and:

#

?var

#

bah. stupid bot.. don't use var

sinful drum
#

Should I use let?

runic sequoia
#

always use const until you can't. only then, use let. never use var.

sinful drum
#

alright

#

thank you

sinful drum
#

the issue is still the same, but I just tested some stuff and when I change the variables thru the console it works

sinful drum
#

gonna try their solutions now

#

the content script should look something like this right?

console.log('Loaded');

chrome.runtime.onMessage.addListener(gotMessage);

window.addEventListener("message", (event) => {
  if (event.source !== window) {
    return;
  }

  if (event.data.type && (event.data.type === "FROM_PAGE")) {
    const p = message.txt[0]
  UPunkte = p
  UKokku = p

  const t = message.txt[1]
  tehteidTasemeti = [0, Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5)]
  console.log("Set");
  }
}, false);
#

gonan convert the script that posts the message now

runic sequoia
#

No that’s not right. message will be undefined.

sinful drum
#

oh

#

right

#

event.data.text should be correct

#
let userinputP
let userinputT
let execute

function setup() {
  noCanvas();

  userinputP = select('#userinputP');
  userinputT = select('#userinputT');
  execute = select('#execute')

  execute.mousePressed(send);
}

function send() {
  const punktid = userinputP.value();
  const tehted = userinputT.value();
  console.log("sent")
   window.postMessage(
    {type : "FROM_PAGE", text: [punktid, tehted]}, "*");
}

for some odd reason the message isn't being posted

#

"sent" is being outputted in the console

#
console.log("Loaded");

chrome.runtime.onMessage.addListener(gotMessage);

window.addEventListener("message", (event) => {
  console.log("Start")
  if (event.source !== window) {
    return;
  }

  if (event.data.type && (event.data.type === "FROM_PAGE")) {
  const p = event.data.text[0]
  UPunkte = p
  UKokku = p

  const t = event.data.text[1]
  tehteidTasemeti = [0, Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5)]
  console.log("Set");
  }
}, false);
#

but here "Start" isn't being outputted into the console

#

could try sending it to the direct url

runic sequoia
#

event.data is what you want, but that doesn't explain why you don't see "Start"
nevermind. you already had event.data...

#

you seem to be missing the chrome.runtime.connect()?

sinful drum
#

uhh

#

didnt realise that

runic sequoia
#

your onMessage is also likely now pointless

sinful drum
#

i think i deleted it because nothing was using it 😅

sinful drum
#

added the runtime.connect thing back

runic sequoia
#

any difference?

sinful drum
#

doesnt look like there are any

var port = chrome.runtime.connect();

console.log("Loaded");

window.addEventListener("message", (event) => {
  console.log("Start")
  if (event.source !== window) {
    return;
  }

  if (event.data.type && (event.data.type === "FROM_PAGE")) {
  const p = event.data[0]
  UPunkte = p
  UKokku = p

  const t = event.data[1]
  tehteidTasemeti = [0, Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5)]
  console.log("Set");
  }
}, false);
#

does it need to be assigned to a variable

#

copied that line from the docs

#

tried it with "var port = " removed still no difference

runic sequoia
#

shouldn't matter

#

not your issue, but this is also wrong:

const p = event.data[0]
sinful drum
#

is event.data.text[0] correct like it was before?

#

chatGPT is saying that postMessage is used for window->window/iframe communication but my extension and window are in the same window

runic sequoia
#

?chatgpt

#

(don't use chatgpt)

sinful drum
sinful drum
#
  }, // i cut out the rest of the manifest since that works fine
  "externally_connectable": {
    "matches": ["https://*.nutisport.eu*"]
  }
}
runic sequoia
#

The URL pattern must contain at least a second-level domain; that is, hostname patterns such as "", ".com", ".co.uk", and ".appspot.com" are not supported. Starting in Chrome 107, you can use <all_urls> to access all domains.
wtf??? in the example, "appspot" would be a second-level domain. so, why is that not allowed?

sinful drum
#

never in my life have i seen a documentation with examples that work

runic sequoia
#

either way, it sounds like you have two options. externally_connectable is for using chrome.runtime.sendMessage() and chrome.runtime.onMessageExternal.addListener()

#

to use window.postMessage(), you need to inject a content script

sinful drum
#

which one do you reckon is more complex to write out?

#

postMessage seems almost done to me

runic sequoia
#

I'm grasping at straws. don't really do extensions, so not sure what works.

sinful drum
#

i have like a few months of c# experience but i havent touched js or html in my entire life

#

gotten pretty far

#

most languages seem like they are identical

sinful drum
runic sequoia
#

I'd walk through the stackoverflow link above and try those suggestions. some are quite detailed

sinful drum
#

is there a way to choose which source I want to edit

#

I feel like this is the problem

#

specifically this file

#

tried most stackOverFlow solutions but they were mostly for other problems

runic sequoia
#

You’re attempting to edit the source in DevTools? That is not going to work…

sinful drum
#

no no

#

im not sure how to word it

#

in inspect element you can like choose what (not sure what you call these) to edit

#

and depending on which one you have chosen currently

#

will offer you different variables to edit

#

correct "source" chosen

#

incorrect "source" chosen

#

i really gotta figure out what those things are called

#

ooh

#

i figured it out

#

its called "javaScript context"

#

depending on which context is chosen is what allows me to edit different variables

#

i just have to change it in the content.js script

#

i think

runic sequoia
#

The links I posted above explain the difference between the various extension scripts and what permissions they have.

runic sequoia
#

No, further back

sinful drum
runic sequoia
#

Yes. Read that first paragraph then scroll to the top and read the whole thing

sinful drum
#

seems like its impossible then

#

gotta stick to executing the script from the console instead of a fancy extension

runic sequoia
#

it's absolutely not impossible. if you read through all of the links above, you can figure it out. people do this with extensions every day.

sinful drum
#

ig i missed something

#

i read that it was talking about how it was isolated and needed events from both side which means i would have to contact the people who made the website

runic sequoia
#

you inject code

#

if you felt like actually taking the time to read any of the links, there's a massive section about injecting.

sinful drum
#

oh i found it

sinful drum
#

found this but im not exactly sure how I would implement this

#

or more exactly how would I run the "actualCode" after declaring it

runic sequoia
#

that is not relevant to what you are attempting

sinful drum
#

i thought i needed script injection

runic sequoia
#

you do.

sinful drum
#

how come that isnt the solution then

runic sequoia
#

that is not script injection

sinful drum
#

if this is not it then i honestly dont know what is

#

either the title is a lie or this is actual script injection

runic sequoia
#

it is not. once again, had you actually read the links you were provided, you would understand.

sinful drum
#

I did read the links

#

static, dynamic and programmatic injection

runic sequoia
#

yet you chose to read a completely different document to try to implement it?

sinful drum
#

I tried to find someone using dynamic injection on stackoverflow bc the docs are not exactly the best

#

ill try .registerContentScripts & chrome.scripting.executeScript

sinful drum
#

stuff is going pretty well but my extension got locked or something

#

i think its because of the manifest or html file

#
{
  "manifest_version": 3,
  "name": "nsScript",
  "version": "3.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "content_security_policy":{ "extension_pages": "default-src 'self'" },
  "permissions": ["tabs", "activeTab", "scripting"],
  "browser_action": {
    "default_popup": "sketch/index.html",
    "default_title": "nsScript"
  }
}
#
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>nsScript</title>
    <script type="text/javascript" src="sketch.js"></script>
  </head>
  <body>
    <h1>nsScript</h1>
    <p>
    <input id="userinputP" placeholder="Punktide arv" />
    <input id="userinputT" placeholder="Tehete arv"/>
    <button type="button" id="execute">Execute</button>
  </p>
  </body>
</html>
#

looks fine to me

#

i think the problem is inside "content_security_policy" because i just dont understand that part at all

#

this is what the directory looks like

#

showing it because I think the index and sketch.js have to be in the same place as the manifest

#

ok that wasnt it

#

moved all the files into the same folder tho

#
{
  "manifest_version": 3,
  "name": "nsScript",
  "version": "3.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "content_security_policy":{ "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self';",
  "sandbox": "sandbox allow-scripts allow-forms allow-popups allow-modals; script-src 'self' 'unsafe-inline' 'unsafe-eval'; child-src 'self';"
 },
  "permissions": ["tabs", "activeTab", "scripting"],
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "nsScript"
  }
}

this should be like the most relaxed security policy yet my extension is still locked

runic sequoia
#

click on "background.html" here: chrome://extensions/ and read the console?

sinful drum
#

background.html?

#

i clicked some button and it showed me the errors in my extension

#

hopefully the last thing i gotta change for mv3

runic sequoia
#

there you go

sinful drum
#

i got the injection working

#

just gotta inject it into the right place/context

runic sequoia
#

ideally, you inject a message event listener which accepts arguments, rather than hard-coding your arguments

sinful drum
#

ill try that as soon as i figure out how to inject it into the right context

#

would "sisufreim" be the id of the iframe I want to inject the script into?

#

thats the context I need to inject into

runic sequoia
#

LOL no clue. you tell us! probably?

sinful drum
#

i have an idea

#

1 sec

#

doesnt look like allFrames: true is accessing the right context

#

UKokku should be an int

sinful drum
runic sequoia
#

wat?

sinful drum
#

the context/iframe id

runic sequoia
#

that has nothing to do with allFrames or all_frames, but cool?

#

pro tip: pasting random error messages with zero context/code is not useful

sinful drum
#

They are not that random

#

But uhh

#

Ill be gone for a couple of hours

runic sequoia
#

at this point you need to put all of your code on github and let people try/tweak it

sinful drum
#

Theres a community where i can do that?

runic sequoia
#

if you don't know git/github, yes you should go learn it now. CVS is very important for programming.

sinful drum
#

my project is on github already but i didnt know I could share it so people can help me

#

i still dont think executing a script in a different javaScript context from a extension should be this hard/tedious

runic sequoia
#

so there are security implications all around. the extension has to work around those security restrictions, which adds some of the complications. then you're using iframes beyond that, which have their own security concerns. overall, it's not that complicated, but your scenario requires pretty-much the most complication

#

if it's on github, share the link

sinful drum
#

gotta update to the most recent version rq

sinful drum
#

i always forget how delicate (i think it is at least) web related stuff is

#

thank you for all the help tho

#

i'd probably have given up without you

#

learned a lot as well

runic sequoia
#
Cannot listen to an undefined element. [Caught in: Tried to listen to element of type click]
#

content.js is empty

#

and sketch.js is all sorts of funky

#
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

chrome.scripting.executeScript({
  target: { tabId: tab.id },
  function: injectedFunction,
});

// The body of this function will be executed as a content script inside the
// current page
function injectedFunction() {
  document.body.style.backgroundColor = 'pink';
}
#

so, you want something to happen when a button is clicked on the webpage, regardless of whether-or-not the extension popup has been shown. correct?

if so, you need to be injecting your script (see above) inside your background service worker. otherwise, nothing will happen unless you open the popup.

#

I have verified the above executeScript() works, you'd just need to tweak it to do what you actually want (listen for the button click)

sinful drum
sinful drum
runic sequoia
#

I'm aware, but that's not where you should be adding the event listener.

sinful drum
#

or if i remember correctly background cant be used for listening

runic sequoia
#

it can absolutely be used for communication between your extension and the webpage you're trying to listen to.

#

I suppose content might work? either way, where you have it is wrong.

sinful drum
#

even if i fix it how would I inject the script into the correct context?

#

scripting.executeScript accepts frames

#

as a target

runic sequoia
#

there is an option to execute on every frame. your code should test whether-or-not it's the correct frame.

sinful drum
#

by checking if the variables exist right?

runic sequoia
#

that's one way. I believe you can test the frame's origin/URL also.

sinful drum
#

choosing the more complex methods hasn't worked out well for me

#

luckily the extension doesnt have to be that optimized since the button just needs to be clicked every now and a then

runic sequoia
#

please try to explain in more detail exactly what you want the behavior of your extension to be.

sinful drum
#

when opening the extension a popup should appear where the user can enter 2 values
after the user has entered the values and pressed the button a js script should execute in a targeted javaScript context (to access the variables that need to be changed)

#

but yeah
click button inside extension popup -> execute/inject a script into a targeted javaScript context

runic sequoia
#

"to access the variables that need to be changed" is what needs explanation. what do you expect changing variables to accomplish? are you changing these in devtools and it does what you want it to do?

sinful drum
#

ill make a quick video of changing the variables manually

#

that will probably explain it better since im not that good at explaining with words

#

i was accidentally in the right context so i switched it to what the default ("top") was

#

but im basically trying to do that but via js script

#

change context and execute a script

#

but changing them in the console works as seen in the video

#

mainly because im in the right context

#

and i can see that the variables exist

runic sequoia
#

will look later tonight.

#

essentially: content or background script adds an event listener waiting for messages. then your popup script sends those messages when you click the execute button.

#

event listener changes variable based on the message

sinful drum
#

i can most of it, but i still need to change the context to access the variables

#

Wrong context chosen "top"

#

Correct context chosen "sisufreim (sisu.php)"

#

this should make it more clear

sinful drum
#

ooooohhhh

#

"sisufreim (sisu.php)" is an iFrame after all

#

i might know what to do

#

ill try it when i wake up

sinful drum
#

alr so im currently in the correct frame but when i try to see the id it just shows -> ''

#

cant go to sleep

#

im way too close

#
function injectedFunction(p, t){
  console.log("Attempting to change")
  if (typeof UPunkte == 'undefined') {return;}
  UPunkte = p
  UKokku = p

  tehteidTasemeti = [0, Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5), Math.round(t/5)]
  console.log("Set");
}

Tried using all frames and an if statement to check if the variable is defined

#

nothing gets past the if statement

#
<IFRAME id="ifrm" name="ifrm" width="50" height="30" src="nutimati.php?mode=blank" style="visibility:hidden"></IFRAME>

I think this is the html line that creates the iFrame im looking for

#

I dont understand why it asks for the frame ids and when i pass the frame ids it says i need an int???

#

this explains it pretty well

sinful drum
#

no idea how to find it tho

#

nvm im gonna go get some rest after all

runic sequoia
#

The Tabs API can be used by the service worker and extension pages, but not content scripts.

#

so, it does need to be in a background service worker

runic sequoia
#

content.js

console.log('content', window.location.href);

if (window.location.href.includes('sisu.php')) {
  console.log('in sisu frame');

  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('message', message);
    if (message.action === 'DO_MY_THING') {
      const { userInputP, userInputT } = message;
      console.log(`DO_MY_THING with: ${userInputP} and ${userInputT}`);
    }
    return true;
  });
}

sketch.js

const userinputP = document.getElementById("userinputP");
const userinputT = document.getElementById("userinputT");
const execute = document.getElementById("execute");

execute.addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.tabs.sendMessage(tab.id, {
    action: 'DO_MY_THING',
    userInputP: userinputP.value,
    userInputT: userinputT.value
  }, (response) => {
    console.log('response', response);
  });
});

manifest.json

{
  "manifest_version": 3,
  "name": "nsScript",
  "version": "3.0",
  "content_scripts": [
    {
      "matches": ["https://nutisport.eu/*"],
      "js": ["content.js"],
      "all_frames": true
    }
  ],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self';"
  },
  "permissions": ["tabs", "activeTab", "scripting"],
  "action": {
    "default_popup": "index.html",
    "default_title": "nsScript"
  }
}
#

I think you need to add a mutation observer to the sisu frame. its content is changing without the frame reloading

#

or maybe you need to hook a different frame. clicking the house opens several frames

content.js:1 content https://nutisport.eu/var17/mati/nharj/algebra.php
content.js:1 content https://nutisport.eu/var17/mati/nharj/nutimati.php?ngr=algebra&nhj=Koondamine
content.js:1 content https://nutisport.eu/var17/mati/nharj/nutimati.php?mode=blank
#

I've spent far too much time on this one. g'luck!